﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using XQ.SP.BllServices;
using XQ.SP.Model;
using XM.Comm;
using XM.PermissionFilter;
using Newtonsoft.Json;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Web.Script.Serialization;
using NPOI.XSSF.UserModel;
using System.Text;
using XM.Models;
using System.IO;
using System.Text.RegularExpressions;

namespace XiaoQu.Controllers
{
    /// <summary>
    /// 检查详细
    /// </summary>
    [Description("检查详细")]
    public class UserInfoCheckController : Controller
    {
        XQ.SP.BllServices.UserInfoCheckBLL bllBase = new XQ.SP.BllServices.UserInfoCheckBLL();

        #region 报表

        [Description("报表")]
        [PermissionFilter]
        public ActionResult Rep()
        {
            string city = Request.Form["City"],
                town = Request.Form["Town"],
                village = Request.Form["Village"],
                beginTime = Request.Form["BeginTime"],
                endTime = Request.Form["EndTime"];

            ViewBag.SearchCity = city;
            ViewBag.SearchTown = town;
            ViewBag.SearchVillage = village;
            ViewBag.SearchBeginTime = beginTime;
            ViewBag.SearchEndTime = endTime;

            // 生成縣鄉村的下拉，根据登录用户
            var where = " 1=1 ";
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
                Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
                Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                if (!string.IsNullOrEmpty(Citys))
                {
                    where += " and City = '" + Citys + "' ";
                    if (string.IsNullOrWhiteSpace(city))
                        city = Citys;
                }
                if (!string.IsNullOrEmpty(Towns))
                {
                    where += " and Towns = '" + Towns + "' ";
                    if (string.IsNullOrWhiteSpace(town))
                        town = Towns;
                }
                if (!string.IsNullOrEmpty(Village))
                {
                    where += " and Village = '" + Village + "' ";
                    if (string.IsNullOrWhiteSpace(village))
                        village = Village;
                }
            }
            XQ.SP.BllServices.UserInfoBLL bll = new XQ.SP.BllServices.UserInfoBLL();
            var list = bll.GetModelList(where);

            ViewBag.City = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(list);

            #region

            //            string s = @"
            //select 
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%') as 应检人数,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and State='已验证') as 累计检测人数,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and  JiWang='是') as 累计既往,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and  Status=1) as 累计新发现,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and   State='已验证' and DateDiff(dd,Modified,getdate())=0) as 本日检测人数,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and   JiWang='是' and DateDiff(dd,Modified,getdate())=0) as 本日既往,
            //(select COUNT(*) from dbo.UserInfoCheck where Towns like '%" + valueStr + @"%' and   Status=1 and DateDiff(dd,Modified,getdate())=0) as 本日新发现
            //";
            //            string s = @"
            //                        select 
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%') as 应检人数,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and CanJiaJian='是') as 累计检测人数,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and  CanJiaJian='是' and  JiWang='是' and JieGuo='阳性') as 累计既往,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and    CanJiaJian='是' and  JiWang='否' and JieGuo='阳性') as 累计新发现,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and   CanJiaJian='是' and DateDiff(dd,Modified,getdate())=0) as 本日检测人数,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and   CanJiaJian='是' and  JiWang='是' and JieGuo='阳性' and DateDiff(dd,Modified,getdate())=0) as 本日既往,
            //                        (select COUNT(*) from dbo.UserInfoCheck where Towns like '%%' and     CanJiaJian='是' and  JiWang='否' and JieGuo='阳性' and DateDiff(dd,Modified,getdate())=0) as 本日新发现
            //                        ";
            #endregion


            where = "";
            string group = "";
            if (!string.IsNullOrWhiteSpace(village))
            {
                group = "*";
                where = " and Village = '" + village.Trim() + "'";
            }
            else if (!string.IsNullOrWhiteSpace(town))
            {
                group = "Village";
                where = " and Towns = '" + town.Trim() + "'";
            }
            else if (!string.IsNullOrWhiteSpace(city))
            {
                group = "Towns";
                where = " and Citys = '" + city.Trim() + "'";
            }
            if (string.IsNullOrWhiteSpace(where))
            {
                group = "Citys";
            }

            DateTime begin, end;
            if (DateTime.TryParse(beginTime, out begin))
            {
                where += " and CanJiaTime > '" + beginTime + "'";
            }
            if (DateTime.TryParse(endTime, out end))
            {
                where += " and CanJiaTime < '" + endTime + "'";
            }

            string sql = "";
            // 村不为空就统计自己的
            if (!string.IsNullOrWhiteSpace(village))
            {
                sql = "select  '" + village + @"', 
    (select COUNT(*) from dbo.UserInfoCheck where 1=1 {0}) as 应检人数,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0}) as 累计检测,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0} and  JIWang='是') as 累计既往,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0} and  JIWang='否' and JieGuo='阳性') as 累计新发现,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0} and DateDiff(dd,CanJiaTime,getdate())=0) as 本日检测,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0} and  JIWang='是' and JieGuo='阳性' and DateDiff(dd,CanJiaTime,getdate())=0) as 本日既往,
    (select COUNT(*) from dbo.UserInfoCheck where CanJiaJian='是' {0} and  JIWang='否' and JieGuo='阳性' and DateDiff(dd,CanJiaTime,getdate())=0) as 本日新发现";
                sql = sql.FormatWith(where);
            }
            else
            {
                // 市、县、乡按县、乡、村分组统计
                sql = @"SELECT A.{0},isnull(YJRS,0) AS YJRS,isnull(LJJC,0) AS LJJC,isnull(LJJW,0) AS LJJW,isnull(LJXFX,0) AS LJXFX,isnull(BRJC,0) AS BRJC,isnull(BRJW,0) AS BRJW,isnull(BRXFX,0) AS BRXFX FROM (
	--应检人数
	SELECT {0},COUNT({0}) AS YJRS FROM dbo.UserInfoCheck WHERE 1=1 {1} GROUP BY {0}) A
	LEFT JOIN (
	--累计检测
	SELECT {0},COUNT({0}) AS LJJC FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} GROUP BY {0}) B ON B.{0}=A.{0}
	LEFT JOIN (
	--累计既往
	SELECT {0},COUNT({0}) AS LJJW FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} AND JIWang='是' GROUP BY {0}) C ON C.{0}=A.{0}
	LEFT JOIN (
	--累计新发现
	SELECT {0},COUNT({0}) AS LJXFX FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} AND JIWang='否' and JieGuo='阳性' GROUP BY {0}) D ON D.{0}=A.{0}
	LEFT JOIN (
	--本日检测
	SELECT {0},COUNT({0}) AS BRJC FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} AND DateDiff(dd,CanJiaTime,getdate())=0 GROUP BY {0}) E ON E.{0}=A.{0}
	LEFT JOIN (
	--本日既往
	SELECT {0},COUNT({0}) AS BRJW FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} AND JIWang='是' AND JieGuo='阳性' AND DateDiff(dd,CanJiaTime,getdate())=0 GROUP BY {0}) F ON F.{0}=A.{0}
	LEFT JOIN (
	--本日新发现
	SELECT {0},COUNT({0}) AS BRXFX FROM dbo.UserInfoCheck WHERE CanJiaJian='是' {1} AND JIWang='否' AND JieGuo='阳性' AND DateDiff(dd,CanJiaTime,getdate())=0 GROUP BY {0}) G ON G.{0}=A.{0}";
                sql = sql.FormatWith(group, where);
            }

            var dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];

            // 导出Excel
            string handler = Request.Form["handler"];
            if (handler == "export")
            {
                //创建Excel文件的对象XLSX
                var book = new XSSFWorkbook();
                //添加一个sheet
                var sheet1 = book.CreateSheet("Sheet1");

                //给sheet1添加第一行的头部标题
                NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                row1.CreateCell(0).SetCellValue("区域");
                row1.CreateCell(1).SetCellValue("应检数");
                row1.CreateCell(2).SetCellValue("累计检测人数");
                row1.CreateCell(3).SetCellValue("累计既往");
                row1.CreateCell(4).SetCellValue("累计新发现");
                row1.CreateCell(5).SetCellValue("本日检测人数");
                row1.CreateCell(6).SetCellValue("本日既往");
                row1.CreateCell(7).SetCellValue("本日新发现");

                // 统计行
                int col1 = 0, col2 = 0, col3 = 0, col4 = 0, col5 = 0, col6 = 0, col7 = 0;

                //将数据逐步写入sheet1各个行
                for (int i = 0, l = dt.Rows.Count; i < l; i++)
                {
                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                    rowtemp.CreateCell(0).SetCellValue(dt.Rows[i][0].ToString());
                    rowtemp.CreateCell(1).SetCellValue(Convert.ToInt32(dt.Rows[i][1]));
                    rowtemp.CreateCell(2).SetCellValue(Convert.ToInt32(dt.Rows[i][2]));
                    rowtemp.CreateCell(3).SetCellValue(Convert.ToInt32(dt.Rows[i][3]));
                    rowtemp.CreateCell(4).SetCellValue(Convert.ToInt32(dt.Rows[i][4]));
                    rowtemp.CreateCell(5).SetCellValue(Convert.ToInt32(dt.Rows[i][5]));
                    rowtemp.CreateCell(6).SetCellValue(Convert.ToInt32(dt.Rows[i][6]));
                    rowtemp.CreateCell(7).SetCellValue(Convert.ToInt32(dt.Rows[i][7]));
                    col1 += Convert.ToInt32(dt.Rows[i][1]);
                    col2 += Convert.ToInt32(dt.Rows[i][2]);
                    col3 += Convert.ToInt32(dt.Rows[i][3]);
                    col4 += Convert.ToInt32(dt.Rows[i][4]);
                    col5 += Convert.ToInt32(dt.Rows[i][5]);
                    col6 += Convert.ToInt32(dt.Rows[i][6]);
                    col7 += Convert.ToInt32(dt.Rows[i][7]);
                }
                // 统计行
                NPOI.SS.UserModel.IRow totalRow = sheet1.CreateRow(dt.Rows.Count + 1);
                totalRow.CreateCell(0).SetCellValue("总计");
                totalRow.CreateCell(1).SetCellValue(col1);
                totalRow.CreateCell(2).SetCellValue(col2);
                totalRow.CreateCell(3).SetCellValue(col3);
                totalRow.CreateCell(4).SetCellValue(col4);
                totalRow.CreateCell(5).SetCellValue(col5);
                totalRow.CreateCell(6).SetCellValue(col6);
                totalRow.CreateCell(7).SetCellValue(col7);


                XQ.Common.Images img = new XQ.Common.Images();
                string saveas = Server.MapPath("~" + img.GetPath()) + "报表-" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx";

                // 写入到客户端 
                System.IO.MemoryStream ms;
                using (ms = new System.IO.MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(saveas, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }

                return File(saveas, "application/vnd.ms-excel", "报表.xlsx");
            }

            ViewBag.dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];

            return View();
        }

        #endregion

        #region 导入、导出

        [HttpPost]
        public ActionResult UFileStu(HttpPostedFileBase file)
        {
            var result = new { status = true, msg = "成功导入数据，请刷新页面" };

            UserInfoItem user = null;
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            else
            {
                user = (UserInfoItem)Session["Users"];
            }

            try
            {

                string fileT = file.FileName;
                if (fileT.Length > 10)
                {
                    fileT = fileT.Substring(fileT.Length - 10);
                }
                fileT = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileT;
                XQ.Common.Images img = new XQ.Common.Images();
                string savePath = img.GetTempPath();
                string uploadPath = Server.MapPath("~" + savePath);

                file.SaveAs(uploadPath + fileT);

                //DataTable dt = GetDataFromExcelByConn(root + fileName);

                var npoi = new NPOIExcelHelper(uploadPath + fileT);
                DataTable dt = npoi.ReadExcel("Sheet1", 0, true);

                // 生成批量导入DataTable
                DataTable dt1 = new DataTable();
                #region
                dt1.Columns.AddRange(new DataColumn[] {   
                            new DataColumn("No",typeof(string)),  
                            new DataColumn("Citys",typeof(string)),  
                            new DataColumn("Towns",typeof(string)),  
                            new DataColumn("Village",typeof(string)),  
                            new DataColumn("Name",typeof(string)),  
                            new DataColumn("Sex",typeof(string)),  
                            new DataColumn("UID",typeof(string)),  
                            new DataColumn("Nation",typeof(string)),   
                            new DataColumn("ZhiYe",typeof(string)), 
                            new DataColumn("HunYing",typeof(string)),  
                            new DataColumn("WenHua",typeof(string)),
                            new DataColumn("ShangHu",typeof(string)),  
                            new DataColumn("BuNaRu",typeof(string)),  
                            new DataColumn("YiNian",typeof(string)),  
                            new DataColumn("CanJiaTi",typeof(string)),  
                            new DataColumn("CanJiaJian",typeof(string)),  
                            new DataColumn("CanJiaTime",typeof(DateTime)),  
                            new DataColumn("JieGuo",typeof(string)),  
                            new DataColumn("JIWang",typeof(string)),  
                            new DataColumn("CaiXue",typeof(string)),  
                            new DataColumn("FuCha",typeof(string)),  
                            new DataColumn("JieGuoHIV",typeof(string)),  
                            new DataColumn("WeiJianCe",typeof(string)),  
                            new DataColumn("Desc",typeof(string)),  
                            new DataColumn("State",typeof(string)),  
                            new DataColumn("StateTime",typeof(DateTime)),  
                            new DataColumn("Id",typeof(long)),  
                            new DataColumn("Status",typeof(int)),  
                            new DataColumn("Creator",typeof(long)),  
                            new DataColumn("Created",typeof(string)),  
                            new DataColumn("Modifier",typeof(long)),  
                            new DataColumn("Modified",typeof(DateTime)),  
                            new DataColumn("Images",typeof(string)),  
                            new DataColumn("BatchNo",typeof(string)),  
                            new DataColumn("Change",typeof(short))
                        });
                #endregion

                XQ.SP.BllServices.UserInfoCheckBLL bllui = new XQ.SP.BllServices.UserInfoCheckBLL();

                // 查询所有数据方便比对
                //var list = bllui.GetModelList();
                //var list = bllui.GetUidList();

                // 生成操作导入批次号
                var batchNo = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                // 开始记录操作日志
                XM.ExceptionAttribute.HandleLog("1、开始执行导入操作\r\n操作用户：" + user.UserName + "\r\n操作批次：" + batchNo + "\r\nExcel数据行数：" + dt.Rows.Count, user.UserName);

                var repeat = new List<string>();
                var delete = new List<string>();

                foreach (DataRow dr in dt.Rows)
                {
                    // 校验姓名不能为空
                    if (dr[4] == null || string.IsNullOrEmpty(dr[4].ToString().Trim()))
                    {
                        continue;
                    }

                    #region 废弃
                    //string uid = string.Empty;
                    ////bool exist = false;
                    //XQ.SP.Model.UserInfoCheckItem itemUi = null;
                    //if (dr[6] != null && !string.IsNullOrEmpty(dr[6].ToString().Trim()))
                    //{
                    //    uid = dr[6].ToString().Trim();

                    //    // 校验身份證是否已经存在
                    //    //itemUi = list.Find(p => p.UID == dr[6].ToString().Trim());
                    //    //itemUi = bllui.GetModelWhereStr(" UID='" + dr[6].ToString().Trim() + "' ");

                    //    //if (list.Contains(uid))
                    //    //{
                    //    //    //exist = true;
                    //    //    delete.Add(uid);
                    //    //}

                    //    //// 如果存在多条数据(>1)则说明数据有重复
                    //    ////if (list.Count(p => p.UID == dr[6].ToString().Trim()) > 1)
                    //    ////{
                    //    ////    repeat.Add(itemUi.UID);
                    //    ////}

                    //    //if (list.FindAll(p => p == uid).Count > 1)
                    //    //{
                    //    //    repeat.Add(itemUi.UID);
                    //    //    continue;
                    //    //}

                    //    //var temp = new List<string>() { uid};
                    //    //IEnumerable<string> has = list.Intersect(temp);  // A∩B 集合A与集合B的交集
                    //    //var count = has.Count();

                    //    var count = list.FindAll(p => p == uid).Count;

                    //    if (count > 0)
                    //    {
                    //        delete.Add(uid);
                    //    }
                    //    if (count > 1)
                    //    {
                    //        repeat.Add(itemUi.UID);
                    //        continue;
                    //    }
                    //}

                    /*if (exist)
                    {
                        #region Update

                        itemUi = new UserInfoCheckItem();

                        itemUi.No = dr[0] == null ? "" : dr[0].ToString().Trim();
                        itemUi.Citys = dr[1] == null ? "" : dr[1].ToString().Trim();
                        itemUi.Towns = dr[2] == null ? "" : dr[2].ToString().Trim();
                        itemUi.Village = dr[3] == null ? "" : dr[3].ToString().Trim();
                        itemUi.Name = dr[4] == null ? "" : dr[4].ToString().Trim();
                        itemUi.Sex = dr[5] == null ? "" : dr[5].ToString().Trim();
                        itemUi.UID = dr[6] == null ? "" : dr[6].ToString().Trim();
                        itemUi.Nation = dr[7] == null ? "" : dr[7].ToString().Trim();
                        itemUi.ZhiYe = dr[8] == null ? "" : dr[8].ToString().Trim();
                        itemUi.HunYing = dr[9] == null ? "" : dr[9].ToString().Trim();
                        itemUi.WenHua = dr[10] == null ? "" : dr[10].ToString().Trim();
                        itemUi.ShangHu = dr[11] == null ? "" : dr[11].ToString().Trim();
                        itemUi.BuNaRu = dr[12] == null ? "" : dr[12].ToString().Trim();
                        itemUi.YiNian = dr[13] == null ? "" : dr[13].ToString().Trim();
                        itemUi.CanJiaTi = dr[14] == null ? "" : dr[14].ToString().Trim();
                        itemUi.CanJiaJian = dr[15] == null ? "" : dr[15].ToString().Trim();
                        if (dr[16] != null && !string.IsNullOrWhiteSpace(dr[16].ToString()))
                        {
                            var time = DateTime.Now;
                            if (DateTime.TryParse(dr[16].ToString().Trim(), out time))
                                itemUi.CanJiaTime = time;
                            else
                                itemUi.CanJiaTime = DateTime.MinValue;
                        }
                        else
                            itemUi.CanJiaTime = DateTime.MinValue;
                        itemUi.JieGuo = dr[17] == null ? "" : dr[17].ToString().Trim();
                        itemUi.JiWang = dr[18] == null ? "" : dr[18].ToString().Trim();
                        itemUi.CaiXue = dr[19] == null ? "" : dr[19].ToString().Trim();
                        itemUi.FuCha = dr[20] == null ? "" : dr[20].ToString().Trim();
                        itemUi.JieGuoHIV = dr[21] == null ? "" : dr[21].ToString().Trim();
                        itemUi.WeiJianCe = dr[22] == null ? "" : dr[22].ToString().Trim();
                        itemUi.Desc = dr[23] == null ? "" : dr[23].ToString().Trim();

                        itemUi.Modified = DateTime.Now;
                        itemUi.Change = 2;

                        // 中途增加字段，兼容处理
                        if (dr.ItemArray.Length > 24)
                        {
                            itemUi.State = dr[24] == null ? "" : dr[24].ToString().Trim();
                        }

                        bllui.UpdateByUid(itemUi);

                        #endregion
                    }
                    else
                    {*/

                    #endregion

                    #region Insert

                    DataRow dr1 = dt1.NewRow();
                    dr1[0] = dr[0] == null ? "" : dr[0].ToString().Trim();
                    dr1[1] = dr[1] == null ? "" : dr[1].ToString().Trim();
                    dr1[2] = dr[2] == null ? "" : dr[2].ToString().Trim();
                    dr1[3] = dr[3] == null ? "" : dr[3].ToString().Trim();
                    dr1[4] = dr[4] == null ? "" : dr[4].ToString().Trim();
                    dr1[5] = dr[5] == null ? "" : dr[5].ToString().Trim();
                    dr1[6] = dr[6] == null ? "" : dr[6].ToString().Trim().ToUpper();
                    dr1[7] = dr[7] == null ? "" : dr[7].ToString().Trim();
                    dr1[8] = dr[8] == null ? "" : dr[8].ToString().Trim();
                    dr1[9] = dr[9] == null ? "" : dr[9].ToString().Trim();
                    dr1[10] = dr[10] == null ? "" : dr[10].ToString().Trim();
                    dr1[11] = dr[11] == null ? "" : dr[11].ToString().Trim();
                    dr1[12] = dr[12] == null ? "" : dr[12].ToString().Trim();
                    dr1[13] = dr[13] == null ? "" : dr[13].ToString().Trim();
                    dr1[14] = dr[14] == null ? "" : dr[14].ToString().Trim();
                    dr1[15] = dr[15] == null ? "" : dr[15].ToString().Trim();
                    if (dr[16] != null && !string.IsNullOrWhiteSpace(dr[16].ToString()))
                    {
                        DateTime dTime;
                        if (DateTime.TryParse(dr[16].ToString().Trim(), out dTime))
                        {
                            dr1[16] = dTime;
                        }
                    }
                    dr1[17] = dr[17] == null ? "" : dr[17].ToString().Trim();
                    dr1[18] = dr[18] == null ? "" : dr[18].ToString().Trim();
                    dr1[19] = dr[19] == null ? "" : dr[19].ToString().Trim();
                    dr1[20] = dr[20] == null ? "" : dr[20].ToString().Trim();
                    dr1[21] = dr[21] == null ? "" : dr[21].ToString().Trim();
                    dr1[22] = dr[22] == null ? "" : dr[22].ToString().Trim();
                    dr1[23] = dr[23] == null ? "" : dr[23].ToString().Trim();
                    dr1[28] = user.Id;
                    dr1[29] = DateTime.Now;
                    dr1[30] = user.Id;
                    dr1[31] = DateTime.Now;
                    dr1[33] = batchNo;
                    dr1[34] = 0;

                    // 中途增加字段，兼容处理
                    if (dr.ItemArray.Length > 24)
                    {
                        dr1[24] = dr[24] == null ? "" : dr[24].ToString().Trim();
                    }

                    dt1.Rows.Add(dr1);

                    #endregion

                    //// 新数据追加到list中，避免同Excel重复
                    //var newItem = new UserInfoCheckItem();
                    //newItem.UID = dr[6].ToString().Trim();

                    //if (!string.IsNullOrWhiteSpace(uid))
                    //{
                    //    list.Add(uid);
                    //}

                    //}
                }

                // 开始记录操作日志
                XM.ExceptionAttribute.HandleLog("2、执行导入操作（BulkCopy）\r\n操作批次：" + batchNo + "\r\n导入数据行数：" + dt1.Rows.Count, user.UserName);

                //if (delete.Count > 0)
                //{
                //    if (!bllui.DeleteListByUid("'" + string.Join("','", delete) + "'"))
                //    {
                //        // 开始记录操作日志
                //        XM.ExceptionAttribute.HandleLog("3、执行导入操作（删除已存在）异常\r\n操作批次：" + batchNo);

                //        throw new Exception("批量导入出现异常");
                //    }
                //}

                // 批量插入
                if (dt1.Rows.Count > 0)
                {
                    if (!bllui.BulkCopy(dt1, batchNo, 5000))
                    {
                        // 开始记录操作日志
                        XM.ExceptionAttribute.HandleLog("3、执行导入操作（BulkCopy）异常\r\n操作批次：" + batchNo, user.UserName);

                        throw new Exception("批量导入出现异常");
                    }
                }

                //if (repeat.Count > 0)
                //{
                //    result = new { status = true, msg = "成功导入数据，请刷新页面。重复身份证号码：" + string.Join(",", repeat) };

                //    XM.ExceptionAttribute.HandleLog("4、重复身份证号码：" + string.Join(",", repeat));
                //}

                XM.ExceptionAttribute.HandleLog("5、导入数据执行结束。操作批次：" + batchNo, user.UserName);
            }
            catch (Exception ex)
            {
                result = new { status = false, msg = "导入数据失败，" + ex.Message };

                XM.ExceptionAttribute.HandleException(ex);
            }

            //return RedirectToAction("List");
            return new ContentResult
            {
                Content = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(new { result }),
                ContentType = "application/json"
            };
        }

        DataTable GetDataFromExcelByConn(string filePath = "")
        {
            //OpenFileDialog openFile = new OpenFileDialog();
            //openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            //openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //openFile.Multiselect = false;
            //if (openFile.ShowDialog() == DialogResult.Cancel) return null;
            //var filePath = openFile.FileName;
            string fileType = System.IO.Path.GetExtension(filePath);
            //if (string.IsNullOrEmpty(fileType)) return null;

            bool hasTitle = false;
            //string filePath = "";

            using (DataSet ds = new DataSet())
            {
                //string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;" +
                //                "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=1;\";" +
                //                "data source={3};",
                //                (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);
                string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;" +
                                "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=2;\";" +
                                "data source={3};",
                                (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);
                string strCom = " SELECT * FROM [Sheet1$]";
                using (OleDbConnection myConn = new OleDbConnection(strCon))
                using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
                {
                    myConn.Open();
                    myCommand.Fill(ds);
                }
                if (ds == null || ds.Tables.Count <= 0) return null;
                return ds.Tables[0];
            }
        }

        public DataSet ExcelToDS(string Path)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            return ds;
        }

        //导出excel
        public FileResult ExportExcel()
        {
            //XQ.SP.BllServices.UserInfoCheckBLL bll = new XQ.SP.BllServices.UserInfoCheckBLL();

            //// 根据登录用户导出数据
            //var where = " 1=1 ";
            //if (Session["Users"] == null)
            //{
            //    where += " and 1<>1";
            //}
            //else
            //{
            //    var user = (UserInfoItem)Session["Users"];

            //    string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
            //    Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
            //    Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

            //    if (!string.IsNullOrEmpty(Citys))
            //    {
            //        where += " and Citys = '" + Citys + "' ";
            //    }
            //    if (!string.IsNullOrEmpty(Towns))
            //    {
            //        where += " and Towns = '" + Towns + "' ";
            //    }
            //    if (!string.IsNullOrEmpty(Village))
            //    {
            //        where += " and Village = '" + Village + "' ";
            //    }
            //}

            ////获取list数据
            //var list = bll.GetModelList(where);

            //创建Excel文件的对象XLSX
            var book = new XSSFWorkbook();
            //添加一个sheet
            var sheet1 = book.CreateSheet("Sheet1");

            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("编码");
            row1.CreateCell(1).SetCellValue("县市");
            row1.CreateCell(2).SetCellValue("乡镇");
            row1.CreateCell(3).SetCellValue("村组名称");
            row1.CreateCell(4).SetCellValue("姓名");
            row1.CreateCell(5).SetCellValue("性别");
            row1.CreateCell(6).SetCellValue("身份证号");
            row1.CreateCell(7).SetCellValue("民族");
            row1.CreateCell(8).SetCellValue("职业");
            row1.CreateCell(9).SetCellValue("婚姻");
            row1.CreateCell(10).SetCellValue("文化程度");
            row1.CreateCell(11).SetCellValue("未上户原因");
            row1.CreateCell(12).SetCellValue("不纳入筛查原因");
            row1.CreateCell(13).SetCellValue("近一年外出时间(月)");
            row1.CreateCell(14).SetCellValue("是否参加2017-2018年体检");
            row1.CreateCell(15).SetCellValue("本次是否参加现场检测");
            row1.CreateCell(16).SetCellValue("检测时间");
            row1.CreateCell(17).SetCellValue("现场HIV初筛结果");
            row1.CreateCell(18).SetCellValue("是否为既往病例");
            row1.CreateCell(19).SetCellValue("是否采血");
            row1.CreateCell(20).SetCellValue("HIV复检结果");
            row1.CreateCell(21).SetCellValue("HIV确证结果");
            row1.CreateCell(22).SetCellValue("未检测原因");
            row1.CreateCell(23).SetCellValue("备注");
            row1.CreateCell(24).SetCellValue("是否户籍人口");
            row1.CreateCell(25).SetCellValue("是否照片");

            // 循环处理，每次读取5万条
            int totalPage = 0;
            int pageIndex = 0;
            int pageSize = 50000;
            do
            {
                pageIndex += 1;
                XQ.Model.Pager.Pager pager = new XQ.Model.Pager.Pager();
                pager.tableName = " UserInfoCheck ";
                pager.fldName = " * ";
                pager.pageSize = pageSize;
                pager.page = pageIndex;
                pager.fldSort = " Id ";
                pager.sort = 1;
                pager.id = " Id ";
                pager.dist = 1;
                pager.strCondition = "";
                if (Session["Users"] == null)
                {
                    pager.strCondition += " and 1<>1";
                }
                else
                {
                    var user = (UserInfoItem)Session["Users"];

                    string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
                    Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
                    Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                    if (!string.IsNullOrEmpty(Citys))
                    {
                        pager.strCondition += " and Citys = '" + Citys + "' ";
                    }
                    if (!string.IsNullOrEmpty(Towns))
                    {
                        pager.strCondition += " and Towns = '" + Towns + "' ";
                    }
                    if (!string.IsNullOrEmpty(Village))
                    {
                        pager.strCondition += " and Village = '" + Village + "' ";
                    }
                }

                pager = DBUtility.DbHelperSQL.GetPage(pager);
                totalPage = pager.pageCount;
                List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(pager.dt);

                //将数据逐步写入sheet1各个行
                for (int i = 0, l = list.Count; i < l; i++)
                {
                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(pageSize * (pageIndex - 1) + i + 1);
                    rowtemp.CreateCell(0).SetCellValue(list[i].No);
                    rowtemp.CreateCell(1).SetCellValue(list[i].Citys);
                    rowtemp.CreateCell(2).SetCellValue(list[i].Towns);
                    rowtemp.CreateCell(3).SetCellValue(list[i].Village);
                    rowtemp.CreateCell(4).SetCellValue(list[i].Name);
                    rowtemp.CreateCell(5).SetCellValue(list[i].Sex);
                    rowtemp.CreateCell(6).SetCellValue(list[i].UID);
                    rowtemp.CreateCell(7).SetCellValue(list[i].Nation);
                    rowtemp.CreateCell(8).SetCellValue(list[i].ZhiYe);
                    rowtemp.CreateCell(9).SetCellValue(list[i].HunYing);
                    rowtemp.CreateCell(10).SetCellValue(list[i].WenHua);
                    rowtemp.CreateCell(11).SetCellValue(list[i].ShangHu);
                    rowtemp.CreateCell(12).SetCellValue(list[i].BuNaRu);
                    rowtemp.CreateCell(13).SetCellValue(list[i].YiNian);
                    rowtemp.CreateCell(14).SetCellValue(list[i].CanJiaTi);
                    rowtemp.CreateCell(15).SetCellValue(list[i].CanJiaJian);
                    if (list[i].CanJiaTime == DateTime.MinValue)
                        rowtemp.CreateCell(16).SetCellValue(string.Empty);
                    else
                        rowtemp.CreateCell(16).SetCellValue(list[i].CanJiaTime.ToString());
                    rowtemp.CreateCell(17).SetCellValue(list[i].JieGuo);
                    rowtemp.CreateCell(18).SetCellValue(list[i].JiWang);
                    rowtemp.CreateCell(19).SetCellValue(list[i].CaiXue);
                    rowtemp.CreateCell(20).SetCellValue(list[i].FuCha);
                    rowtemp.CreateCell(21).SetCellValue(list[i].JieGuoHIV);
                    rowtemp.CreateCell(22).SetCellValue(list[i].WeiJianCe);
                    rowtemp.CreateCell(23).SetCellValue(list[i].Desc);
                    rowtemp.CreateCell(24).SetCellValue(list[i].State);
                    rowtemp.CreateCell(25).SetCellValue(string.IsNullOrWhiteSpace(list[i].Images) ? "否" : "是");
                }
            } while (totalPage >= pageIndex + 1);

            XQ.Common.Images img = new XQ.Common.Images();
            string saveas = Server.MapPath("~" + img.GetTempPath()) + "人员信息-" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + (new Random()).Next(10000, 99999) + ".xlsx";

            // 写入到客户端 
            System.IO.MemoryStream ms;
            using (ms = new System.IO.MemoryStream())
            {
                //book.Write(ms);
                //ms.Flush();
                //ms.Seek(0, SeekOrigin.Begin);
                //book = null;

                book.Write(ms);
                using (FileStream fs = new FileStream(saveas, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
                book = null;
            }

            return File(saveas, "application/vnd.ms-excel", "人员信息.xlsx");
        }

        #endregion

        #region 列表、重复

        [Description("列表")]
        [PermissionFilter]
        public ActionResult List()
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "no", Text = "编号", Selected = search_type == "no" });
            ListSeach.Add(new SelectListItem { Value = "citys", Text = "县市", Selected = search_type == "citys" });
            ListSeach.Add(new SelectListItem { Value = "towns", Text = "乡镇", Selected = search_type == "towns" });
            ListSeach.Add(new SelectListItem { Value = "village", Text = "村组名称", Selected = search_type == "village" });
            ListSeach.Add(new SelectListItem { Value = "name", Text = "姓名", Selected = search_type == "name" });
            ListSeach.Add(new SelectListItem { Value = "nation", Text = "民族", Selected = search_type == "nation" });
            ListSeach.Add(new SelectListItem { Value = "uid", Text = "身份证", Selected = search_type == "uid" });
            ListSeach.Add(new SelectListItem { Value = "yinian", Text = "近一年外出时间", Selected = search_type == "yinian" });
            ListSeach.Add(new SelectListItem { Value = "jieguo", Text = "现场HIV初筛结果", Selected = search_type == "jieguo" });
            ListSeach.Add(new SelectListItem { Value = "jiwang", Text = "是否为既往病例", Selected = search_type == "jiwang" });
            ListSeach.Add(new SelectListItem { Value = "fucha", Text = "HIV复检结", Selected = search_type == "fucha" });
            ListSeach.Add(new SelectListItem { Value = "jieguohiv", Text = "HIV确证结果", Selected = search_type == "jieguohiv" });
            ListSeach.Add(new SelectListItem { Value = "desc", Text = "备注", Selected = search_type == "desc" });
            ListSeach.Add(new SelectListItem { Value = "photo", Text = "照片(是、否)", Selected = search_type == "photo" });
            ViewBag.ListSeachType = ListSeach;

            ViewBag.SeachValue = valueStr;

            // 根据登录用户导出数据
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                // 前端删除按钮
                ViewBag.Admin = user.UserName == "5134" ? "1" : "0";
            }

            return View();
        }

        // 查询重复
        [Description("列表")]
        [PermissionFilter]
        public ActionResult RepeatList(int pageIndex = 1)
        {
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "no", Text = "编号" });
            ListSeach.Add(new SelectListItem { Value = "citys", Text = "县市" });
            ListSeach.Add(new SelectListItem { Value = "towns", Text = "乡镇" });
            ListSeach.Add(new SelectListItem { Value = "village", Text = "村组名称" });
            ListSeach.Add(new SelectListItem { Value = "name", Text = "姓名" });
            ListSeach.Add(new SelectListItem { Value = "nation", Text = "民族" });
            ListSeach.Add(new SelectListItem { Value = "uid", Text = "身份证" });
            ListSeach.Add(new SelectListItem { Value = "yinian", Text = "近一年外出时间" });
            ListSeach.Add(new SelectListItem { Value = "jieguo", Text = "现场HIV初筛结果" });
            ListSeach.Add(new SelectListItem { Value = "jiwang", Text = "是否为既往病例" });
            ListSeach.Add(new SelectListItem { Value = "fucha", Text = "HIV复检结" });
            ListSeach.Add(new SelectListItem { Value = "jieguohiv", Text = "HIV确证结果" });
            ListSeach.Add(new SelectListItem { Value = "desc", Text = "备注" });
            ListSeach.Add(new SelectListItem { Value = "photo", Text = "照片(是、否)" });
            ViewBag.ListSeachType = ListSeach;

            #region

            int pageSize = 9999;
            string where = " ";

            // 根据登录用户导出数据
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                // 前端删除按钮
                ViewBag.Admin = user.UserName == "5134" ? "1" : "0";

                string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
               Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
               Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                if (!string.IsNullOrEmpty(Citys))
                {
                    where += " and Citys = '" + Citys + "' ";
                }
                if (!string.IsNullOrEmpty(Towns))
                {
                    where += " and Towns = '" + Towns + "' ";
                }
                if (!string.IsNullOrEmpty(Village))
                {
                    where += " and Village = '" + Village + "' ";
                }
            }

            string sql = @"
SELECT A.* FROM UserInfoCheck A,(
 SELECT UID,count(UID) AS NUM FROM UserInfoCheck
 GROUP BY UID HAVING count(*)>1
) AS B
WHERE B.UID=A.UID " + where;


            var dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];
            #endregion

            List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(dt);
            return View("List", new PagedList<XQ.SP.Model.UserInfoCheckItem>(list, pageIndex, pageSize, dt.Rows.Count));
        }

        // 导出重复
        public FileResult ExportRepeatExcel()
        {
            XQ.SP.BllServices.UserInfoCheckBLL bll = new XQ.SP.BllServices.UserInfoCheckBLL();

            // 根据登录用户导出数据
            var where = " ";
            if (Session["Users"] == null)
            {
                where += " and 1<>1";
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
               Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
               Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                if (!string.IsNullOrEmpty(Citys))
                {
                    where += " and Citys = '" + Citys + "' ";
                }
                if (!string.IsNullOrEmpty(Towns))
                {
                    where += " and Towns = '" + Towns + "' ";
                }
                if (!string.IsNullOrEmpty(Village))
                {
                    where += " and Village = '" + Village + "' ";
                }
            }
            string sql = @"
SELECT A.* FROM UserInfoCheck A,(
 SELECT UID,count(UID) AS NUM FROM UserInfoCheck
 GROUP BY UID HAVING count(*)>1
) AS B
WHERE B.UID=A.UID " + where;

            var dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];
            var list = bllBase.DataTableToList(dt);

            //获取list数据
            //var list = bll.GetModelList(where);

            //创建Excel文件的对象XLSX
            var book = new XSSFWorkbook();
            //添加一个sheet
            var sheet1 = book.CreateSheet("Sheet1");

            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("编码");
            row1.CreateCell(1).SetCellValue("县市");
            row1.CreateCell(2).SetCellValue("乡镇");
            row1.CreateCell(3).SetCellValue("村组名称");
            row1.CreateCell(4).SetCellValue("姓名");
            row1.CreateCell(5).SetCellValue("性别");
            row1.CreateCell(6).SetCellValue("身份证号");
            row1.CreateCell(7).SetCellValue("民族");
            row1.CreateCell(8).SetCellValue("职业");
            row1.CreateCell(9).SetCellValue("婚姻");
            row1.CreateCell(10).SetCellValue("文化程度");
            row1.CreateCell(11).SetCellValue("未上户原因");
            row1.CreateCell(12).SetCellValue("不纳入筛查原因");
            row1.CreateCell(13).SetCellValue("近一年外出时间(月)");
            row1.CreateCell(14).SetCellValue("是否参加2017-2018年体检");
            row1.CreateCell(15).SetCellValue("本次是否参加现场检测");
            row1.CreateCell(16).SetCellValue("检测时间");
            row1.CreateCell(17).SetCellValue("现场HIV初筛结果");
            row1.CreateCell(18).SetCellValue("是否为既往病例");
            row1.CreateCell(19).SetCellValue("是否采血");
            row1.CreateCell(20).SetCellValue("HIV复检结果");
            row1.CreateCell(21).SetCellValue("HIV确证结果");
            row1.CreateCell(22).SetCellValue("未检测原因");
            row1.CreateCell(23).SetCellValue("备注");
            row1.CreateCell(24).SetCellValue("是否户籍人口");

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].No);
                rowtemp.CreateCell(1).SetCellValue(list[i].Citys);
                rowtemp.CreateCell(2).SetCellValue(list[i].Towns);
                rowtemp.CreateCell(3).SetCellValue(list[i].Village);
                rowtemp.CreateCell(4).SetCellValue(list[i].Name);
                rowtemp.CreateCell(5).SetCellValue(list[i].Sex);
                rowtemp.CreateCell(6).SetCellValue(list[i].UID);
                rowtemp.CreateCell(7).SetCellValue(list[i].Nation);
                rowtemp.CreateCell(8).SetCellValue(list[i].ZhiYe);
                rowtemp.CreateCell(9).SetCellValue(list[i].HunYing);
                rowtemp.CreateCell(10).SetCellValue(list[i].WenHua);
                rowtemp.CreateCell(11).SetCellValue(list[i].ShangHu);
                rowtemp.CreateCell(12).SetCellValue(list[i].BuNaRu);
                rowtemp.CreateCell(13).SetCellValue(list[i].YiNian);
                rowtemp.CreateCell(14).SetCellValue(list[i].CanJiaTi);
                rowtemp.CreateCell(15).SetCellValue(list[i].CanJiaJian);
                if (list[i].CanJiaTime == DateTime.MinValue)
                    rowtemp.CreateCell(16).SetCellValue(string.Empty);
                else
                    rowtemp.CreateCell(16).SetCellValue(list[i].CanJiaTime.ToString());
                rowtemp.CreateCell(17).SetCellValue(list[i].JieGuo);
                rowtemp.CreateCell(18).SetCellValue(list[i].JiWang);
                rowtemp.CreateCell(19).SetCellValue(list[i].CaiXue);
                rowtemp.CreateCell(20).SetCellValue(list[i].FuCha);
                rowtemp.CreateCell(21).SetCellValue(list[i].JieGuoHIV);
                rowtemp.CreateCell(22).SetCellValue(list[i].WeiJianCe);
                rowtemp.CreateCell(23).SetCellValue(list[i].Desc);
                rowtemp.CreateCell(24).SetCellValue(list[i].State);
            }

            XQ.Common.Images img = new XQ.Common.Images();
            string saveas = Server.MapPath("~" + img.GetTempPath()) + "重复人员信息-" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx";

            // 写入到客户端 
            System.IO.MemoryStream ms;
            using (ms = new System.IO.MemoryStream())
            {
                //book.Write(ms);
                //ms.Flush();
                //ms.Seek(0, SeekOrigin.Begin);
                //book = null;

                book.Write(ms);
                using (FileStream fs = new FileStream(saveas, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
                book = null;
            }

            return File(saveas, "application/vnd.ms-excel", "重复人员信息.xlsx");
        }

        // 删除重复
        [Description("删除")]
        [PermissionFilter]
        public JsonResult DeleteRepeat()
        {
            var where = " ";
            if (Session["Users"] == null)
            {
                where += " and 1<>1";
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
                Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
                Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                if (!string.IsNullOrEmpty(Citys))
                {
                    where += " and Citys = '" + Citys + "' ";
                }
                if (!string.IsNullOrEmpty(Towns))
                {
                    where += " and Towns = '" + Towns + "' ";
                }
                if (!string.IsNullOrEmpty(Village))
                {
                    where += " and Village = '" + Village + "' ";
                }
            }
            string sql = @"
DELETE UserInfoCheck WHERE Id IN (
    SELECT A.Id FROM UserInfoCheck A,(
     SELECT UID,count(UID) AS NUM FROM UserInfoCheck
     GROUP BY UID HAVING count(*)>1
    ) AS B
    WHERE B.UID=A.UID" + where + @"
)";


            if (DBUtility.DbHelperSQL.ExecuteSql(sql) > 0)
                return Json("true", JsonRequestBehavior.AllowGet);

            return Json("false", JsonRequestBehavior.AllowGet);
        }

        // Ajax异步取数
        public JsonResult CheckList()
        {
            string pageIndex = Request.Params["pageIndex"],
                pageSize = Request.Params["pageSize"],
                valueStr = Request.Params["search_input"],
                search_type = Request.Params["search_type"],
                isSearchDel = Request.Params["isSearchDel"],
                isRepeat = Request.Params["isRepeat"];

            int pgSize = 20, pgIndex = 1;
            if (!int.TryParse(pageSize, out pgSize))
            {
                pgSize = 20;
            }
            if (!int.TryParse(pageIndex, out pgIndex))
            {
                pgIndex = 20;
            }

            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfoCheck ";
            modelP.fldName = " * ";
            modelP.pageSize = pgSize;
            modelP.page = pgIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            modelP.strCondition = "";
            if (!string.IsNullOrEmpty(valueStr))
            {
                if (search_type == "photo")
                {
                    if (valueStr == "是")
                        modelP.strCondition += " and Images IS NOT NULL ";
                    else
                        modelP.strCondition += " and Images IS NULL ";

                }
                else
                {
                    modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
                }
            }

            // 根据登录用户导出数据
            if (Session["Users"] == null)
            {
                //return RedirectToAction("LoginUIA", "User");
                modelP.strCondition += " and 1<>1 ";
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];

                string Citys = string.IsNullOrWhiteSpace(user.City) ? null : user.City.Trim(),
                Towns = string.IsNullOrWhiteSpace(user.Towns) ? null : user.Towns.Trim(),
                Village = string.IsNullOrWhiteSpace(user.Village) ? null : user.Village.Trim();

                if (!string.IsNullOrEmpty(Citys))
                {
                    modelP.strCondition += " and Citys = '" + Citys + "' ";
                }
                if (!string.IsNullOrEmpty(Towns))
                {
                    modelP.strCondition += " and Towns = '" + Towns + "' ";
                }
                if (!string.IsNullOrEmpty(Village))
                {
                    modelP.strCondition += " and Village = '" + Village + "' ";
                }

                // 查询重复的数据
                #region
                if (isRepeat == "1")
                {
                    string where = "";
                    if (!string.IsNullOrEmpty(Citys))
                    {
                        where += " and Citys = '" + Citys + "' ";
                    }
                    if (!string.IsNullOrEmpty(Towns))
                    {
                        where += " and Towns = '" + Towns + "' ";
                    }
                    if (!string.IsNullOrEmpty(Village))
                    {
                        where += " and Village = '" + Village + "' ";
                    }

                    var top = (pgIndex + 1) * pgSize;
                    string sql = @"
SELECT TOP " + pgSize + @" * FROM (
SELECT TOP " + top + @" A.* FROM UserInfoCheck A,(
 SELECT UID,count(UID) AS NUM FROM UserInfoCheck
 GROUP BY UID HAVING count(*)>1
) AS B
WHERE B.UID=A.UID " + where + @" 
) AS C";

                    var dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];

                    var list1 = bllBase.DataTableToList(dt);
                    var json1 = new
                    {
                        total = list1.Count,
                        pageIndex = pgIndex,
                        pageSize = pgSize,
                        items = list1
                    };

                    return Json(json1, JsonRequestBehavior.AllowGet);
                }
                #endregion
            }

            // 删除数据
            if (isSearchDel == "1" && !string.IsNullOrWhiteSpace(modelP.strCondition))
            {
                string sql = @"DELETE UserInfoCheck WHERE 1=1 " + modelP.strCondition;
                DBUtility.DbHelperSQL.ExecuteSql(sql);
            }

            modelP = DBUtility.DbHelperSQL.GetPage(modelP);

            List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(modelP.dt);

            var json = new
            {
                total = modelP.counts,
                pageIndex = pgIndex,
                pageSize = pgSize,
                items = list
            };

            //JsonSerializerSettings serializer = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
            //return Json(JsonConvert.SerializeObject(json, Formatting.Indented, serializer).Replace("\r\n", ""), JsonRequestBehavior.AllowGet);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 编辑

        [Description("编辑")]
        [PermissionFilter]
        public ActionResult Edit(long id = 0, int tid = 0)
        {
            // 根据登录用户
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            var user = (UserInfoItem)Session["Users"];
            if (user.UserName != "5134")
            {
                return View("NoEdit");
            }

            UserInfoCheckItem item = new UserInfoCheckItem();

            //item.CanJiaTime = DateTime.Now.AddYears(-20);
            //item.StateTime = DateTime.Now.AddYears(-20);
            item.Status = tid;
            if (id != 0)
            {
                item = bllBase.GetModel(id);
            }

            List<SelectListItem> ListSex = new List<SelectListItem>();
            ListSex.Add(new SelectListItem { Value = "男", Text = "男" });
            ListSex.Add(new SelectListItem { Value = "女", Text = "女" });
            ViewBag.ListSex = ListSex;
            List<SelectListItem> ListZhiYe = new List<SelectListItem>();
            ListZhiYe.Add(new SelectListItem { Value = "工人", Text = "工人" });
            ListZhiYe.Add(new SelectListItem { Value = "农民", Text = "农民" });
            ListZhiYe.Add(new SelectListItem { Value = "个体", Text = "个体" });
            ListZhiYe.Add(new SelectListItem { Value = "服务业", Text = "服务业" });
            ListZhiYe.Add(new SelectListItem { Value = "干部", Text = "干部" });
            ListZhiYe.Add(new SelectListItem { Value = "学生", Text = "学生" });
            ListZhiYe.Add(new SelectListItem { Value = "无业", Text = "无业" });
            ListZhiYe.Add(new SelectListItem { Value = "其他", Text = "其他" });
            ViewBag.ListZhiYe = ListZhiYe;
            List<SelectListItem> ListHunYing = new List<SelectListItem>();
            ListHunYing.Add(new SelectListItem { Value = "未婚", Text = "未婚" });
            ListHunYing.Add(new SelectListItem { Value = "已婚有配偶", Text = "已婚有配偶" });
            ListHunYing.Add(new SelectListItem { Value = "离异或丧偶", Text = "离异或丧偶" });
            ViewBag.ListHunYing = ListHunYing;
            List<SelectListItem> ListWenHua = new List<SelectListItem>();
            ListWenHua.Add(new SelectListItem { Value = "文盲", Text = "文盲" });
            ListWenHua.Add(new SelectListItem { Value = "小学", Text = "小学" });
            ListWenHua.Add(new SelectListItem { Value = "初中", Text = "初中" });
            ListWenHua.Add(new SelectListItem { Value = "高中或中专", Text = "高中或中专" });
            ListWenHua.Add(new SelectListItem { Value = "大专及以上", Text = "大专及以上" });
            ViewBag.ListWenHua = ListWenHua;
            List<SelectListItem> ListShangHu = new List<SelectListItem>();
            ListShangHu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListShangHu.Add(new SelectListItem { Value = "出生未上户", Text = "出生未上户" });
            ListShangHu.Add(new SelectListItem { Value = "搬迁/嫁入未迁户", Text = "搬迁/嫁入未迁户" });
            ViewBag.ListShangHu = ListShangHu;

            List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            ListBuNaRu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            //ViewBag.ListBuNaRu = ListBuNaRu;
            List<SelectListItem> ListBuNaRu2 = new List<SelectListItem>();
            //ListBuNaRu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListBuNaRu.Add(new SelectListItem { Value = "死亡", Text = "死亡" });
            ListBuNaRu.Add(new SelectListItem { Value = "搬迁/外嫁至县外", Text = "搬迁/外嫁至县外" });
            ListBuNaRu.Add(new SelectListItem { Value = "参军", Text = "参军" });
            ListBuNaRu.Add(new SelectListItem { Value = "县外工作", Text = "县外工作" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押县外", Text = "羁押县外" });
            ListBuNaRu.Add(new SelectListItem { Value = "空挂户", Text = "空挂户" });
            ListBuNaRu.Add(new SelectListItem { Value = "失联/失踪", Text = "失联/失踪" });
            ListBuNaRu.Add(new SelectListItem { Value = "未满18月龄", Text = "未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "异地筛查乡镇参加检测", Text = "异地筛查乡镇参加检测" });
            //ViewBag.ListBuNaRu2 = ListBuNaRu2;
            ViewBag.ListBuNaRu = ListBuNaRu;


            List<SelectListItem> ListJieGuo = new List<SelectListItem>();
            ListJieGuo.Add(new SelectListItem { Value = "无", Text = "无" });
            ListJieGuo.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListJieGuo.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListJieGuo = ListJieGuo;

            List<SelectListItem> ListFuCha = new List<SelectListItem>();
            ListFuCha.Add(new SelectListItem { Value = "无", Text = "无" });
            ListFuCha.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListFuCha.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListFuCha = ListFuCha;

            List<SelectListItem> ListJieGuoHIV = new List<SelectListItem>();
            ListJieGuoHIV.Add(new SelectListItem { Value = "无", Text = "无" });
            ListJieGuoHIV.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListJieGuoHIV.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListJieGuoHIV = ListJieGuoHIV;


            List<SelectListItem> ListCanJiaTi = new List<SelectListItem>();
            ListCanJiaTi.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCanJiaTi.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaTi.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaTi = ListCanJiaTi;
            List<SelectListItem> ListCanJiaJian = new List<SelectListItem>();
            ListCanJiaJian.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCanJiaJian.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaJian.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaJian = ListCanJiaJian;
            List<SelectListItem> ListCaiXue = new List<SelectListItem>();
            ListCaiXue.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCaiXue.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCaiXue.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCaiXue = ListCaiXue;
            List<SelectListItem> ListWeiJianCe = new List<SelectListItem>();
            ListWeiJianCe.Add(new SelectListItem { Value = "无", Text = "无" });
            ListWeiJianCe.Add(new SelectListItem { Value = "拒绝检测", Text = "拒绝检测" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后死亡", Text = "摸底后死亡" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后羁押", Text = "摸底后羁押" });
            ListWeiJianCe.Add(new SelectListItem { Value = "因精神疾病无法检测", Text = "因精神疾病无法检测" });
            ViewBag.ListWeiJianCe = ListWeiJianCe;
            List<SelectListItem> ListState = new List<SelectListItem>();
            ListState.Add(new SelectListItem { Value = "否", Text = "否" });
            ListState.Add(new SelectListItem { Value = "是", Text = "是" });
            ViewBag.ListState = ListState;

            return View(item);
        }

        [Description("编辑")]
        [PermissionFilter]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(UserInfoCheckItem model)
        {
            #region old
            //List<SelectListItem> ListSex = new List<SelectListItem>();
            //ListSex.Add(new SelectListItem { Value = "男", Text = "男" });
            //ListSex.Add(new SelectListItem { Value = "女", Text = "女" });
            //ViewBag.ListSex=ListSex;
            //List<SelectListItem> ListZhiYe = new List<SelectListItem>();
            //ListZhiYe.Add(new SelectListItem { Value = "工人", Text = "工人" });
            //ListZhiYe.Add(new SelectListItem { Value = "农民", Text = "农民" });
            //ListZhiYe.Add(new SelectListItem { Value = "个体", Text = "个体" });
            //ListZhiYe.Add(new SelectListItem { Value = "服务业", Text = "服务业" });
            //ListZhiYe.Add(new SelectListItem { Value = "干部", Text = "干部" });
            //ListZhiYe.Add(new SelectListItem { Value = "学生", Text = "学生" });
            //ListZhiYe.Add(new SelectListItem { Value = "无业", Text = "无业" });
            //ListZhiYe.Add(new SelectListItem { Value = "其他", Text = "其他" });
            //ViewBag.ListZhiYe=ListZhiYe;
            //List<SelectListItem> ListHunYing = new List<SelectListItem>();
            //ListHunYing.Add(new SelectListItem { Value = "未婚", Text = "未婚" });
            //ListHunYing.Add(new SelectListItem { Value = "已婚有配偶", Text = "已婚有配偶" });
            //ListHunYing.Add(new SelectListItem { Value = "离异或丧偶", Text = "离异或丧偶" });
            //ViewBag.ListHunYing=ListHunYing;
            //List<SelectListItem> ListWenHua = new List<SelectListItem>();
            //ListWenHua.Add(new SelectListItem { Value = "文盲", Text = "文盲" });
            //ListWenHua.Add(new SelectListItem { Value = "小学", Text = "小学" });
            //ListWenHua.Add(new SelectListItem { Value = "初中", Text = "初中" });
            //ListWenHua.Add(new SelectListItem { Value = "高中或中专", Text = "高中或中专" });
            //ListWenHua.Add(new SelectListItem { Value = "大专及以上", Text = "大专及以上" });
            //ViewBag.ListWenHua=ListWenHua;
            //List<SelectListItem> ListShangHu = new List<SelectListItem>();
            //ListShangHu.Add(new SelectListItem { Value = "出生未上户", Text = "出生未上户" });
            //ListShangHu.Add(new SelectListItem { Value = "搬迁/嫁入未迁户", Text = "搬迁/嫁入未迁户" });
            //ViewBag.ListShangHu=ListShangHu;
            //List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            //ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            //ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            //ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            //ViewBag.ListBuNaRu=ListBuNaRu;
            //List<SelectListItem> ListCanJiaTi = new List<SelectListItem>();
            //ListCanJiaTi.Add(new SelectListItem { Value = "是", Text = "是" });
            //ListCanJiaTi.Add(new SelectListItem { Value = "否", Text = "否" });
            //ViewBag.ListCanJiaTi=ListCanJiaTi;
            //List<SelectListItem> ListCanJiaJian = new List<SelectListItem>();
            //ListCanJiaJian.Add(new SelectListItem { Value = "是", Text = "是" });
            //ListCanJiaJian.Add(new SelectListItem { Value = "否", Text = "否" });
            //ViewBag.ListCanJiaJian=ListCanJiaJian;
            //List<SelectListItem> ListCaiXue = new List<SelectListItem>();
            //ListCaiXue.Add(new SelectListItem { Value = "是", Text = "是" });
            //ListCaiXue.Add(new SelectListItem { Value = "否", Text = "否" });
            //ViewBag.ListCaiXue=ListCaiXue;
            //List<SelectListItem> ListWeiJianCe = new List<SelectListItem>();
            //ListWeiJianCe.Add(new SelectListItem { Value = "拒绝检测", Text = "拒绝检测" });
            //ListWeiJianCe.Add(new SelectListItem { Value = "摸底后死亡", Text = "摸底后死亡" });
            //ListWeiJianCe.Add(new SelectListItem { Value = "摸底后羁押", Text = "摸底后羁押" });
            //ListWeiJianCe.Add(new SelectListItem { Value = "因精神疾病无法检测", Text = "因精神疾病无法检测" });
            //ViewBag.ListWeiJianCe=ListWeiJianCe;
            //List<SelectListItem> ListState = new List<SelectListItem>();
            //ListState.Add(new SelectListItem { Value = "未验证", Text = "未验证" });
            //ListState.Add(new SelectListItem { Value = "已验证", Text = "已验证" });
            //ViewBag.ListState=ListState;
            #endregion

            #region


            List<SelectListItem> ListSex = new List<SelectListItem>();
            ListSex.Add(new SelectListItem { Value = "男", Text = "男" });
            ListSex.Add(new SelectListItem { Value = "女", Text = "女" });
            ViewBag.ListSex = ListSex;
            List<SelectListItem> ListZhiYe = new List<SelectListItem>();
            ListZhiYe.Add(new SelectListItem { Value = "工人", Text = "工人" });
            ListZhiYe.Add(new SelectListItem { Value = "农民", Text = "农民" });
            ListZhiYe.Add(new SelectListItem { Value = "个体", Text = "个体" });
            ListZhiYe.Add(new SelectListItem { Value = "服务业", Text = "服务业" });
            ListZhiYe.Add(new SelectListItem { Value = "干部", Text = "干部" });
            ListZhiYe.Add(new SelectListItem { Value = "学生", Text = "学生" });
            ListZhiYe.Add(new SelectListItem { Value = "无业", Text = "无业" });
            ListZhiYe.Add(new SelectListItem { Value = "其他", Text = "其他" });
            ViewBag.ListZhiYe = ListZhiYe;
            List<SelectListItem> ListHunYing = new List<SelectListItem>();
            ListHunYing.Add(new SelectListItem { Value = "未婚", Text = "未婚" });
            ListHunYing.Add(new SelectListItem { Value = "已婚有配偶", Text = "已婚有配偶" });
            ListHunYing.Add(new SelectListItem { Value = "离异或丧偶", Text = "离异或丧偶" });
            ViewBag.ListHunYing = ListHunYing;
            List<SelectListItem> ListWenHua = new List<SelectListItem>();
            ListWenHua.Add(new SelectListItem { Value = "文盲", Text = "文盲" });
            ListWenHua.Add(new SelectListItem { Value = "小学", Text = "小学" });
            ListWenHua.Add(new SelectListItem { Value = "初中", Text = "初中" });
            ListWenHua.Add(new SelectListItem { Value = "高中或中专", Text = "高中或中专" });
            ListWenHua.Add(new SelectListItem { Value = "大专及以上", Text = "大专及以上" });
            ViewBag.ListWenHua = ListWenHua;
            List<SelectListItem> ListShangHu = new List<SelectListItem>();
            ListShangHu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListShangHu.Add(new SelectListItem { Value = "出生未上户", Text = "出生未上户" });
            ListShangHu.Add(new SelectListItem { Value = "搬迁/嫁入未迁户", Text = "搬迁/嫁入未迁户" });
            ViewBag.ListShangHu = ListShangHu;

            //List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            //ListBuNaRu.Add(new SelectListItem { Value = "无", Text = "无" });
            //ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            //ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            //ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            //ViewBag.ListBuNaRu = ListBuNaRu;
            //List<SelectListItem> ListBuNaRu2 = new List<SelectListItem>();
            //ListBuNaRu2.Add(new SelectListItem { Value = "无", Text = "无" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "死亡", Text = "死亡" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "搬迁/外嫁至县外", Text = "搬迁/外嫁至县外" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "参军", Text = "参军" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "县外工作", Text = "县外工作" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "羁押县外", Text = "羁押县外" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "空挂户", Text = "空挂户" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "失联/失踪", Text = "失联/失踪" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "未满18月龄", Text = "未满18月龄" });
            //ListBuNaRu2.Add(new SelectListItem { Value = "异地筛查乡镇参加检测", Text = "异地筛查乡镇参加检测" });
            //ViewBag.ListBuNaRu2 = ListBuNaRu2;

            List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            ListBuNaRu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            //ViewBag.ListBuNaRu = ListBuNaRu;
            List<SelectListItem> ListBuNaRu2 = new List<SelectListItem>();
            //ListBuNaRu.Add(new SelectListItem { Value = "无", Text = "无" });
            ListBuNaRu.Add(new SelectListItem { Value = "死亡", Text = "死亡" });
            ListBuNaRu.Add(new SelectListItem { Value = "搬迁/外嫁至县外", Text = "搬迁/外嫁至县外" });
            ListBuNaRu.Add(new SelectListItem { Value = "参军", Text = "参军" });
            ListBuNaRu.Add(new SelectListItem { Value = "县外工作", Text = "县外工作" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押县外", Text = "羁押县外" });
            ListBuNaRu.Add(new SelectListItem { Value = "空挂户", Text = "空挂户" });
            ListBuNaRu.Add(new SelectListItem { Value = "失联/失踪", Text = "失联/失踪" });
            ListBuNaRu.Add(new SelectListItem { Value = "未满18月龄", Text = "未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "异地筛查乡镇参加检测", Text = "异地筛查乡镇参加检测" });
            //ViewBag.ListBuNaRu2 = ListBuNaRu2;
            ViewBag.ListBuNaRu = ListBuNaRu;


            List<SelectListItem> ListJieGuo = new List<SelectListItem>();
            ListJieGuo.Add(new SelectListItem { Value = "无", Text = "无" });
            ListJieGuo.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListJieGuo.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListJieGuo = ListJieGuo;

            List<SelectListItem> ListFuCha = new List<SelectListItem>();
            ListFuCha.Add(new SelectListItem { Value = "无", Text = "无" });
            ListFuCha.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListFuCha.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListFuCha = ListFuCha;

            List<SelectListItem> ListJieGuoHIV = new List<SelectListItem>();
            ListJieGuoHIV.Add(new SelectListItem { Value = "无", Text = "无" });
            ListJieGuoHIV.Add(new SelectListItem { Value = "阳性", Text = "阳性" });
            ListJieGuoHIV.Add(new SelectListItem { Value = "阴性", Text = "阴性" });
            ViewBag.ListJieGuoHIV = ListJieGuoHIV;


            List<SelectListItem> ListCanJiaTi = new List<SelectListItem>();
            ListCanJiaTi.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCanJiaTi.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaTi.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaTi = ListCanJiaTi;
            List<SelectListItem> ListCanJiaJian = new List<SelectListItem>();
            ListCanJiaJian.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCanJiaJian.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaJian.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaJian = ListCanJiaJian;
            List<SelectListItem> ListCaiXue = new List<SelectListItem>();
            ListCaiXue.Add(new SelectListItem { Value = "无", Text = "无" });
            ListCaiXue.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCaiXue.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCaiXue = ListCaiXue;
            List<SelectListItem> ListWeiJianCe = new List<SelectListItem>();
            ListWeiJianCe.Add(new SelectListItem { Value = "无", Text = "无" });
            ListWeiJianCe.Add(new SelectListItem { Value = "拒绝检测", Text = "拒绝检测" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后死亡", Text = "摸底后死亡" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后羁押", Text = "摸底后羁押" });
            ListWeiJianCe.Add(new SelectListItem { Value = "因精神疾病无法检测", Text = "因精神疾病无法检测" });
            ViewBag.ListWeiJianCe = ListWeiJianCe;
            List<SelectListItem> ListState = new List<SelectListItem>();
            ListState.Add(new SelectListItem { Value = "否", Text = "否" });
            ListState.Add(new SelectListItem { Value = "是", Text = "是" });
            ViewBag.ListState = ListState;
            #endregion

            #region
            try
            {
                string s = "";
                if (string.IsNullOrEmpty(model.UID))
                {
                    s = "身份证号不能为空 !";
                    ModelState.AddModelError("", s);
                    return View(model);
                }
                if (string.IsNullOrEmpty(model.Name))
                {
                    s = "名称不能为空 !";
                    ModelState.AddModelError("", s);
                    return View(model);
                }
                if (model.UID.Length < 15)
                    s = "身份证号码长度不对 !";
                if (model.UID.Length > 19)
                    s = "身份证号码长度不对 !";
                if (!string.IsNullOrEmpty(s))
                {
                    ModelState.AddModelError("", s);
                    return View(model);
                }
                if (model.No.Length > 120)
                    s = "编号字符数不能多于120 !";
                if (model.Citys.Length > 120)
                    s = "县市字符数不能多于120 !";
                if (model.Towns.Length > 120)
                    s = "乡镇字符数不能多于120 !";
                if (model.Village.Length > 120)
                    s = "村组名称字符数不能多于120 !";
                if (model.Name.Length > 120)
                    s = "姓名字符数不能多于120 !";
                if (model.Sex.Length > 120)
                    s = "性别(男、女)字符数不能多于120 !";
                if (model.UID.Length > 120)
                    s = "身份证号字符数不能多于120 !";
                if (model.Nation.Length > 120)
                    s = "民族字符数不能多于120 !";
                if (model.ZhiYe.Length > 120)
                    s = "职业(工人、农民、个体、服务业、干部、学生、无业、其他)字符数不能多于120 !";
                if (model.HunYing.Length > 120)
                    s = "婚姻状况(未婚、已婚有配偶、离异或丧偶)字符数不能多于120 !";
                if (model.WenHua.Length > 120)
                    s = "文化程度(文盲、小学、初中、高中或中专、大专及以上)字符数不能多于120 !";
                if (model.ShangHu.Length > 120)
                    s = "未上户原因(出生未上户、搬迁/嫁入未迁户)字符数不能多于120 !";
                if (model.BuNaRu.Length > 120)
                    s = "不纳入筛查原因(流入未满3个月、出生未满18月龄、羁押)字符数不能多于120 !";
                if (model.YiNian.Length > 120)
                    s = "近一年外出时间字符数不能多于120 !";
                if (model.CanJiaTi.Length > 120)
                    s = "是否参加2017-2018年体检(是、否)字符数不能多于120 !";
                if (model.CanJiaJian.Length > 120)
                    s = "本次是否参加现场检测(是、否)字符数不能多于120 !";
                if (model.JieGuo.Length > 120)
                    s = "现场HIV初筛结果字符数不能多于120 !";
                if (model.JiWang.Length > 120)
                    s = "是否为既往病例字符数不能多于120 !";
                if (model.CaiXue.Length > 120)
                    s = "是否采血(是、否)字符数不能多于120 !";
                if (model.FuCha.Length > 120)
                    s = "HIV复检结字符数不能多于120 !";
                if (model.JieGuoHIV.Length > 120)
                    s = "HIV确证结果字符数不能多于120 !";
                if (model.WeiJianCe.Length > 120)
                    s = "未检测原因(拒绝检测、摸底后死亡、摸底后羁押、因精神疾病无法检测)字符数不能多于120 !";
                if (model.Desc.Length > 400)
                    s = "备注字符数不能多于400 !";
                if (model.State.Length > 80)
                    s = "状态(未验证、已验证)字符数不能多于80 !";
                if (model.Images.Length > 400)
                    s = "现场拍照(P1字符数不能多于400 !";
                if (!string.IsNullOrEmpty(s))
                {
                    ModelState.AddModelError("", s);
                    return View(model);
                }
            }
            catch
            {
            }
            #endregion

            #region
            #endregion
            if (model.Id > 0)
            {
                var userCurr = UsersInfo.GetUserH();
                model.Modified = DateTime.Now;
                model.Modifier = userCurr.Id;
                model.Change = 2;
                if (bllBase.Update(model))
                    return RedirectToAction("List");
                else
                {
                    ModelState.AddModelError("", "编辑失败");
                }
            }
            else
            {
                var userCurr = UsersInfo.GetUserH();
                model.Creator = userCurr.Id;
                model.Created = DateTime.Now;
                model.Modified = DateTime.Now;
                model.Change = 1;
                if (bllBase.Add(model) > 0)
                    return RedirectToAction("List");
                else
                {
                    ModelState.AddModelError("", "添加失败");
                }
            }
            return View(model);
        }

        #endregion

        #region 删除
        [Description("删除")]
        [PermissionFilter]
        public JsonResult Deletes(string ids)
        {
            if (bllBase.DeleteList(ids))
            {
                return Json("true");
            }

            return Json("false");
        }
        #endregion

        #region 个人中心

        #region 个人中心列表
        [Description("个人中心列表")]
        [PermissionFilter]
        public ActionResult MyList(int pageIndex = 1)
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "no", Text = "编号" });
            ListSeach.Add(new SelectListItem { Value = "citys", Text = "县市" });
            ListSeach.Add(new SelectListItem { Value = "towns", Text = "乡镇" });
            ListSeach.Add(new SelectListItem { Value = "village", Text = "村组名称" });
            ListSeach.Add(new SelectListItem { Value = "name", Text = "姓名" });
            ListSeach.Add(new SelectListItem { Value = "nation", Text = "民族" });
            ListSeach.Add(new SelectListItem { Value = "yinian", Text = "近一年外出时间" });
            ListSeach.Add(new SelectListItem { Value = "jieguo", Text = "现场HIV初筛结果" });
            ListSeach.Add(new SelectListItem { Value = "jiwang", Text = "是否为既往病例" });
            ListSeach.Add(new SelectListItem { Value = "fucha", Text = "HIV复检结" });
            ListSeach.Add(new SelectListItem { Value = "jieguohiv", Text = "HIV确证结果" });
            ListSeach.Add(new SelectListItem { Value = "desc", Text = "备注" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfoCheck ";
            modelP.fldName = " * ";
            modelP.pageSize = 20;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }
            modelP.strCondition += " and Creator ='" + UsersInfo.GetUsersID() + "' ";
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(modelP.dt);
            return View(new PagedList<XQ.SP.Model.UserInfoCheckItem>(list, pageIndex, pageSize, modelP.counts));
        }
        #endregion

        #region 个人中心编辑
        [Description("个人中心编辑")]
        [PermissionFilter]
        public ActionResult MyEdit(long id = 0, int tid = 0)
        {
            UserInfoCheckItem item = new UserInfoCheckItem();
            item.Status = tid;
            if (id != 0)
            {
                item = bllBase.GetModel(id);
            }



            List<SelectListItem> ListSex = new List<SelectListItem>();
            ListSex.Add(new SelectListItem { Value = "男", Text = "男" });
            ListSex.Add(new SelectListItem { Value = "女", Text = "女" });
            ViewBag.ListSex = ListSex;
            List<SelectListItem> ListZhiYe = new List<SelectListItem>();
            ListZhiYe.Add(new SelectListItem { Value = "工人", Text = "工人" });
            ListZhiYe.Add(new SelectListItem { Value = "农民", Text = "农民" });
            ListZhiYe.Add(new SelectListItem { Value = "个体", Text = "个体" });
            ListZhiYe.Add(new SelectListItem { Value = "服务业", Text = "服务业" });
            ListZhiYe.Add(new SelectListItem { Value = "干部", Text = "干部" });
            ListZhiYe.Add(new SelectListItem { Value = "学生", Text = "学生" });
            ListZhiYe.Add(new SelectListItem { Value = "无业", Text = "无业" });
            ListZhiYe.Add(new SelectListItem { Value = "其他", Text = "其他" });
            ViewBag.ListZhiYe = ListZhiYe;
            List<SelectListItem> ListHunYing = new List<SelectListItem>();
            ListHunYing.Add(new SelectListItem { Value = "未婚", Text = "未婚" });
            ListHunYing.Add(new SelectListItem { Value = "已婚有配偶", Text = "已婚有配偶" });
            ListHunYing.Add(new SelectListItem { Value = "离异或丧偶", Text = "离异或丧偶" });
            ViewBag.ListHunYing = ListHunYing;
            List<SelectListItem> ListWenHua = new List<SelectListItem>();
            ListWenHua.Add(new SelectListItem { Value = "文盲", Text = "文盲" });
            ListWenHua.Add(new SelectListItem { Value = "小学", Text = "小学" });
            ListWenHua.Add(new SelectListItem { Value = "初中", Text = "初中" });
            ListWenHua.Add(new SelectListItem { Value = "高中或中专", Text = "高中或中专" });
            ListWenHua.Add(new SelectListItem { Value = "大专及以上", Text = "大专及以上" });
            ViewBag.ListWenHua = ListWenHua;
            List<SelectListItem> ListShangHu = new List<SelectListItem>();
            ListShangHu.Add(new SelectListItem { Value = "出生未上户", Text = "出生未上户" });
            ListShangHu.Add(new SelectListItem { Value = "搬迁/嫁入未迁户", Text = "搬迁/嫁入未迁户" });
            ViewBag.ListShangHu = ListShangHu;
            List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            ViewBag.ListBuNaRu = ListBuNaRu;
            List<SelectListItem> ListCanJiaTi = new List<SelectListItem>();
            ListCanJiaTi.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaTi.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaTi = ListCanJiaTi;
            List<SelectListItem> ListCanJiaJian = new List<SelectListItem>();
            ListCanJiaJian.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaJian.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaJian = ListCanJiaJian;
            List<SelectListItem> ListCaiXue = new List<SelectListItem>();
            ListCaiXue.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCaiXue.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCaiXue = ListCaiXue;
            List<SelectListItem> ListWeiJianCe = new List<SelectListItem>();
            ListWeiJianCe.Add(new SelectListItem { Value = "拒绝检测", Text = "拒绝检测" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后死亡", Text = "摸底后死亡" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后羁押", Text = "摸底后羁押" });
            ListWeiJianCe.Add(new SelectListItem { Value = "因精神疾病无法检测", Text = "因精神疾病无法检测" });
            ViewBag.ListWeiJianCe = ListWeiJianCe;
            List<SelectListItem> ListState = new List<SelectListItem>();
            ListState.Add(new SelectListItem { Value = "未验证", Text = "未验证" });
            ListState.Add(new SelectListItem { Value = "已验证", Text = "已验证" });
            ViewBag.ListState = ListState;

            return View(item);
        }

        [Description("个人中心编辑")]
        [PermissionFilter]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MyEdit(UserInfoCheckItem model)
        {



            List<SelectListItem> ListSex = new List<SelectListItem>();
            ListSex.Add(new SelectListItem { Value = "男", Text = "男" });
            ListSex.Add(new SelectListItem { Value = "女", Text = "女" });
            ViewBag.ListSex = ListSex;
            List<SelectListItem> ListZhiYe = new List<SelectListItem>();
            ListZhiYe.Add(new SelectListItem { Value = "工人", Text = "工人" });
            ListZhiYe.Add(new SelectListItem { Value = "农民", Text = "农民" });
            ListZhiYe.Add(new SelectListItem { Value = "个体", Text = "个体" });
            ListZhiYe.Add(new SelectListItem { Value = "服务业", Text = "服务业" });
            ListZhiYe.Add(new SelectListItem { Value = "干部", Text = "干部" });
            ListZhiYe.Add(new SelectListItem { Value = "学生", Text = "学生" });
            ListZhiYe.Add(new SelectListItem { Value = "无业", Text = "无业" });
            ListZhiYe.Add(new SelectListItem { Value = "其他", Text = "其他" });
            ViewBag.ListZhiYe = ListZhiYe;
            List<SelectListItem> ListHunYing = new List<SelectListItem>();
            ListHunYing.Add(new SelectListItem { Value = "未婚", Text = "未婚" });
            ListHunYing.Add(new SelectListItem { Value = "已婚有配偶", Text = "已婚有配偶" });
            ListHunYing.Add(new SelectListItem { Value = "离异或丧偶", Text = "离异或丧偶" });
            ViewBag.ListHunYing = ListHunYing;
            List<SelectListItem> ListWenHua = new List<SelectListItem>();
            ListWenHua.Add(new SelectListItem { Value = "文盲", Text = "文盲" });
            ListWenHua.Add(new SelectListItem { Value = "小学", Text = "小学" });
            ListWenHua.Add(new SelectListItem { Value = "初中", Text = "初中" });
            ListWenHua.Add(new SelectListItem { Value = "高中或中专", Text = "高中或中专" });
            ListWenHua.Add(new SelectListItem { Value = "大专及以上", Text = "大专及以上" });
            ViewBag.ListWenHua = ListWenHua;
            List<SelectListItem> ListShangHu = new List<SelectListItem>();
            ListShangHu.Add(new SelectListItem { Value = "出生未上户", Text = "出生未上户" });
            ListShangHu.Add(new SelectListItem { Value = "搬迁/嫁入未迁户", Text = "搬迁/嫁入未迁户" });
            ViewBag.ListShangHu = ListShangHu;
            List<SelectListItem> ListBuNaRu = new List<SelectListItem>();
            ListBuNaRu.Add(new SelectListItem { Value = "流入未满3个月", Text = "流入未满3个月" });
            ListBuNaRu.Add(new SelectListItem { Value = "出生未满18月龄", Text = "出生未满18月龄" });
            ListBuNaRu.Add(new SelectListItem { Value = "羁押", Text = "羁押" });
            ViewBag.ListBuNaRu = ListBuNaRu;
            List<SelectListItem> ListCanJiaTi = new List<SelectListItem>();
            ListCanJiaTi.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaTi.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaTi = ListCanJiaTi;
            List<SelectListItem> ListCanJiaJian = new List<SelectListItem>();
            ListCanJiaJian.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCanJiaJian.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCanJiaJian = ListCanJiaJian;
            List<SelectListItem> ListCaiXue = new List<SelectListItem>();
            ListCaiXue.Add(new SelectListItem { Value = "是", Text = "是" });
            ListCaiXue.Add(new SelectListItem { Value = "否", Text = "否" });
            ViewBag.ListCaiXue = ListCaiXue;
            List<SelectListItem> ListWeiJianCe = new List<SelectListItem>();
            ListWeiJianCe.Add(new SelectListItem { Value = "拒绝检测", Text = "拒绝检测" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后死亡", Text = "摸底后死亡" });
            ListWeiJianCe.Add(new SelectListItem { Value = "摸底后羁押", Text = "摸底后羁押" });
            ListWeiJianCe.Add(new SelectListItem { Value = "因精神疾病无法检测", Text = "因精神疾病无法检测" });
            ViewBag.ListWeiJianCe = ListWeiJianCe;
            List<SelectListItem> ListState = new List<SelectListItem>();
            ListState.Add(new SelectListItem { Value = "未验证", Text = "未验证" });
            ListState.Add(new SelectListItem { Value = "已验证", Text = "已验证" });
            ViewBag.ListState = ListState;

            #region
            try
            {
                string s = "";
                if (model.No.Length > 120)
                    s = "编号字符数不能多于120 !";
                if (model.Citys.Length > 120)
                    s = "县市字符数不能多于120 !";
                if (model.Towns.Length > 120)
                    s = "乡镇字符数不能多于120 !";
                if (model.Village.Length > 120)
                    s = "村组名称字符数不能多于120 !";
                if (model.Name.Length > 120)
                    s = "姓名字符数不能多于120 !";
                if (model.Sex.Length > 120)
                    s = "性别(男、女)字符数不能多于120 !";
                if (model.UID.Length > 120)
                    s = "身份证号字符数不能多于120 !";
                if (model.Nation.Length > 120)
                    s = "民族字符数不能多于120 !";
                if (model.ZhiYe.Length > 120)
                    s = "职业(工人、农民、个体、服务业、干部、学生、无业、其他)字符数不能多于120 !";
                if (model.HunYing.Length > 120)
                    s = "婚姻状况(未婚、已婚有配偶、离异或丧偶)字符数不能多于120 !";
                if (model.WenHua.Length > 120)
                    s = "文化程度(文盲、小学、初中、高中或中专、大专及以上)字符数不能多于120 !";
                if (model.ShangHu.Length > 120)
                    s = "未上户原因(出生未上户、搬迁/嫁入未迁户)字符数不能多于120 !";
                if (model.BuNaRu.Length > 120)
                    s = "不纳入筛查原因(流入未满3个月、出生未满18月龄、羁押)字符数不能多于120 !";
                if (model.YiNian.Length > 120)
                    s = "近一年外出时间字符数不能多于120 !";
                if (model.CanJiaTi.Length > 120)
                    s = "是否参加2017-2018年体检(是、否)字符数不能多于120 !";
                if (model.CanJiaJian.Length > 120)
                    s = "本次是否参加现场检测(是、否)字符数不能多于120 !";
                if (model.JieGuo.Length > 120)
                    s = "现场HIV初筛结果字符数不能多于120 !";
                if (model.JiWang.Length > 120)
                    s = "是否为既往病例字符数不能多于120 !";
                if (model.CaiXue.Length > 120)
                    s = "是否采血(是、否)字符数不能多于120 !";
                if (model.FuCha.Length > 120)
                    s = "HIV复检结字符数不能多于120 !";
                if (model.JieGuoHIV.Length > 120)
                    s = "HIV确证结果字符数不能多于120 !";
                if (model.WeiJianCe.Length > 120)
                    s = "未检测原因(拒绝检测、摸底后死亡、摸底后羁押、因精神疾病无法检测)字符数不能多于120 !";
                if (model.Desc.Length > 400)
                    s = "备注字符数不能多于400 !";
                if (model.State.Length > 80)
                    s = "状态(未验证、已验证)字符数不能多于80 !";
                if (model.Images.Length > 400)
                    s = "现场拍照(P1字符数不能多于400 !";
                if (!string.IsNullOrEmpty(s))
                {
                    ModelState.AddModelError("", s);
                    return View(model);
                }
            }
            catch { }
            #endregion

            #region
            #endregion
            if (model.Id > 0)
            {
                model.Modified = DateTime.Now;
                model.Modifier = UsersInfo.GetUser().Id;
                if (bllBase.Update(model))
                    return RedirectToAction("MyList");
                else
                {
                    ModelState.AddModelError("", "编辑失败");
                }
            }
            else
            {
                model.Creator = UsersInfo.GetUser().Id;
                model.Created = DateTime.Now;
                model.Modified = DateTime.Now;
                if (bllBase.Add(model) > 0)
                    return RedirectToAction("MyList");
                else
                {
                    ModelState.AddModelError("", "添加失败");
                }
            }
            return View(model);
        }
        #endregion

        #region 个人中心删除
        [Description("个人中心删除")]
        [PermissionFilter]
        public ActionResult MyDelete(long id, int pageIndex)
        {
            var item = bllBase.GetModel(id);

            if (bllBase.Delete(id))
                return RedirectToAction("MyList", new { pageIndex = pageIndex });
            else
                return RedirectToAction("MyList");
        }
        #endregion

        #endregion

        #region PC端页面
        #region 查询页面
        [Description("查询页面")]
        [PermissionFilter]
        public ActionResult Sele(int pageIndex = 1)
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "name", Text = "标题" });
            ListSeach.Add(new SelectListItem { Value = "keys", Text = "关键字" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfoCheck ";
            modelP.fldName = " * ";
            modelP.pageSize = 20;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(modelP.dt);

            return View(new PagedList<XQ.SP.Model.UserInfoCheckItem>(list, pageIndex, pageSize, modelP.counts));
        }
        #endregion
        #region 详细
        [Description("详细页面")]
        [PermissionFilter]
        public ActionResult D(long id = 1)
        {
            var item = bllBase.GetModel(id);
            return View(item);
        }
        #endregion
        #endregion

        #region 小程序、App

        // 查询接口
        [Description("实体列表接口")]
        [PermissionFilter]
        public JsonResult Selei(int pageIndex = 1, String No = "", String Citys = "", String Towns = "", String Village = "", String Name = "", String Sex = "", String UID = "", String Nation = "", String ZhiYe = "", String HunYing = "", String WenHua = "", String ShangHu = "", String BuNaRu = "", String YiNian = "", String CanJiaTi = "", String CanJiaJian = "", String CanJiaTime = "", String JieGuo = "", String JIWang = "", String CaiXue = "", String FuCha = "", String JieGuoHIV = "", String WeiJianCe = "", String Desc = "", String State = "", String StateTime = "", Int64 Id = 0, Int32 Status = 0, Int64 Creator = 0, String Created = "", Int64 Modifier = 0, String Modified = "", String Images = "")
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "name", Text = "标题" });
            ListSeach.Add(new SelectListItem { Value = "keys", Text = "关键字" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfoCheck ";
            modelP.fldName = " * ";
            modelP.pageSize = pageSize;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }

            if (!string.IsNullOrEmpty(No))
            {
                modelP.strCondition += " and No like '%" + No + "%' ";
            }
            if (!string.IsNullOrEmpty(Citys))
            {
                modelP.strCondition += " and Citys like '%" + Citys + "%' ";
            }
            if (!string.IsNullOrEmpty(Towns))
            {
                modelP.strCondition += " and Towns like '%" + Towns + "%' ";
            }
            if (!string.IsNullOrEmpty(Village))
            {
                modelP.strCondition += " and Village like '%" + Village + "%' ";
            }
            if (!string.IsNullOrEmpty(Name))
            {
                modelP.strCondition += " and Name like '%" + Name + "%' ";
            }
            if (!string.IsNullOrEmpty(Sex))
            {
                modelP.strCondition += " and Sex like '%" + Sex + "%' ";
            }
            if (!string.IsNullOrEmpty(UID))
            {
                modelP.strCondition += " and UID like '%" + UID + "%' ";
            }
            if (!string.IsNullOrEmpty(Nation))
            {
                modelP.strCondition += " and Nation like '%" + Nation + "%' ";
            }
            if (!string.IsNullOrEmpty(ZhiYe))
            {
                modelP.strCondition += " and ZhiYe like '%" + ZhiYe + "%' ";
            }
            if (!string.IsNullOrEmpty(HunYing))
            {
                modelP.strCondition += " and HunYing like '%" + HunYing + "%' ";
            }
            if (!string.IsNullOrEmpty(WenHua))
            {
                modelP.strCondition += " and WenHua like '%" + WenHua + "%' ";
            }
            if (!string.IsNullOrEmpty(ShangHu))
            {
                modelP.strCondition += " and ShangHu like '%" + ShangHu + "%' ";
            }
            if (!string.IsNullOrEmpty(BuNaRu))
            {
                modelP.strCondition += " and BuNaRu like '%" + BuNaRu + "%' ";
            }
            if (!string.IsNullOrEmpty(YiNian))
            {
                modelP.strCondition += " and YiNian like '%" + YiNian + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaTi))
            {
                modelP.strCondition += " and CanJiaTi like '%" + CanJiaTi + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaJian))
            {
                modelP.strCondition += " and CanJiaJian like '%" + CanJiaJian + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaTime))
            {
                modelP.strCondition += " and CanJiaTime like '%" + CanJiaTime + "%' ";
            }
            if (!string.IsNullOrEmpty(JieGuo))
            {
                modelP.strCondition += " and JieGuo like '%" + JieGuo + "%' ";
            }
            if (!string.IsNullOrEmpty(JIWang))
            {
                modelP.strCondition += " and JIWang like '%" + JIWang + "%' ";
            }
            if (!string.IsNullOrEmpty(CaiXue))
            {
                modelP.strCondition += " and CaiXue like '%" + CaiXue + "%' ";
            }
            if (!string.IsNullOrEmpty(FuCha))
            {
                modelP.strCondition += " and FuCha like '%" + FuCha + "%' ";
            }
            if (!string.IsNullOrEmpty(JieGuoHIV))
            {
                modelP.strCondition += " and JieGuoHIV like '%" + JieGuoHIV + "%' ";
            }
            if (!string.IsNullOrEmpty(WeiJianCe))
            {
                modelP.strCondition += " and WeiJianCe like '%" + WeiJianCe + "%' ";
            }
            if (!string.IsNullOrEmpty(Desc))
            {
                modelP.strCondition += " and Desc like '%" + Desc + "%' ";
            }
            if (!string.IsNullOrEmpty(State))
            {
                modelP.strCondition += " and State like '%" + State + "%' ";
            }
            if (!string.IsNullOrEmpty(StateTime))
            {
                modelP.strCondition += " and StateTime like '%" + StateTime + "%' ";
            }
            if (Id != 0)
            {
                modelP.strCondition += " and Id =" + Id + " ";
            }
            if (Status != 0)
            {
                modelP.strCondition += " and Status =" + Status + " ";
            }
            if (Creator != 0)
            {
                modelP.strCondition += " and Creator =" + Creator + " ";
            }
            if (!string.IsNullOrEmpty(Created))
            {
                modelP.strCondition += " and Created like '%" + Created + "%' ";
            }
            if (Modifier != 0)
            {
                modelP.strCondition += " and Modifier =" + Modifier + " ";
            }
            if (!string.IsNullOrEmpty(Modified))
            {
                modelP.strCondition += " and Modified like '%" + Modified + "%' ";
            }
            if (!string.IsNullOrEmpty(Images))
            {
                modelP.strCondition += " and Images like '%" + Images + "%' ";
            }
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoCheckItem> list = bllBase.DataTableToList(modelP.dt);

            return Json(list, JsonRequestBehavior.AllowGet);
            //return View(new PagedList<XQ.SP.Model.UserInfoCheckItem>(list, pageNo, pageSize, pager.counts));
        }


        // 单个实体接口
        [Description("单个实体接口")]
        [PermissionFilter]
        public JsonResult Di(long id = 0)
        {
            var item = bllBase.GetModel(id);
            return Json(item, JsonRequestBehavior.AllowGet);
        }

        #endregion


        // 下载数据,查询接口
        [Compress]
        [Description("实体列表接口")]
        [PermissionFilter]
        public ActionResult L(int pageNo = 1, int pageSize = 1000, String UserName = "", String Pwd = "", int init = 0, string deviceNo = "", String No = "", String Citys = "", String Towns = "", String Village = "", String Name = "", String Sex = "", String UID = "", String Nation = "", String ZhiYe = "", String HunYing = "", String WenHua = "", String ShangHu = "", String BuNaRu = "", String YiNian = "", String CanJiaTi = "", String CanJiaJian = "", String CanJiaTime = "", String JieGuo = "", String JIWang = "", String CaiXue = "", String FuCha = "", String JieGuoHIV = "", String WeiJianCe = "", String Desc = "", String State = "", String StateTime = "", Int64 Id = 0, Int32 Status = 0, Int64 Creator = 0, String Created = "", Int64 Modifier = 0, String Modified = "", String Images = "")
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "name", Text = "标题" });
            ListSeach.Add(new SelectListItem { Value = "keys", Text = "关键字" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageNo;
            @ViewBag.ListSeachValue = valueStr;

            if (string.IsNullOrEmpty(UserName))
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(Pwd))
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
            XQ.SP.BllServices.UserInfoBLL bllU = new UserInfoBLL();
            var mU = bllU.GetModelWhereStr(" UserName='" + UserName + "' and Pwd='" + Pwd + "' ");
            if (mU == null)
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
            if (!string.IsNullOrWhiteSpace(mU.City))
                Citys = mU.City.Trim();
            if (!string.IsNullOrWhiteSpace(mU.Towns))
                Towns = mU.Towns.Trim();
            if (!string.IsNullOrWhiteSpace(mU.Village))
                Village = mU.Village.Trim();


            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfoCheck ";
            modelP.fldName = " * ";
            modelP.pageSize = pageSize;
            modelP.page = pageNo;
            modelP.fldSort = " UID ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }
            #region

            if (!string.IsNullOrEmpty(No))
            {
                modelP.strCondition += " and No like '%" + No + "%' ";
            }
            if (!string.IsNullOrEmpty(Citys))
            {
                modelP.strCondition += " and Citys = '" + Citys + "' ";
            }
            if (!string.IsNullOrEmpty(Towns))
            {
                modelP.strCondition += " and Towns = '" + Towns + "' ";
            }
            if (!string.IsNullOrEmpty(Village))
            {
                modelP.strCondition += " and Village = '" + Village + "' ";
            }
            if (!string.IsNullOrEmpty(Name))
            {
                modelP.strCondition += " and Name like '%" + Name + "%' ";
            }
            if (!string.IsNullOrEmpty(Sex))
            {
                modelP.strCondition += " and Sex like '%" + Sex + "%' ";
            }
            if (!string.IsNullOrEmpty(UID))
            {
                modelP.strCondition += " and UID like '%" + UID + "%' ";
            }
            if (!string.IsNullOrEmpty(Nation))
            {
                modelP.strCondition += " and Nation like '%" + Nation + "%' ";
            }
            if (!string.IsNullOrEmpty(ZhiYe))
            {
                modelP.strCondition += " and ZhiYe like '%" + ZhiYe + "%' ";
            }
            if (!string.IsNullOrEmpty(HunYing))
            {
                modelP.strCondition += " and HunYing like '%" + HunYing + "%' ";
            }
            if (!string.IsNullOrEmpty(WenHua))
            {
                modelP.strCondition += " and WenHua like '%" + WenHua + "%' ";
            }
            if (!string.IsNullOrEmpty(ShangHu))
            {
                modelP.strCondition += " and ShangHu like '%" + ShangHu + "%' ";
            }
            if (!string.IsNullOrEmpty(BuNaRu))
            {
                modelP.strCondition += " and BuNaRu like '%" + BuNaRu + "%' ";
            }
            if (!string.IsNullOrEmpty(YiNian))
            {
                modelP.strCondition += " and YiNian like '%" + YiNian + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaTi))
            {
                modelP.strCondition += " and CanJiaTi like '%" + CanJiaTi + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaJian))
            {
                modelP.strCondition += " and CanJiaJian like '%" + CanJiaJian + "%' ";
            }
            if (!string.IsNullOrEmpty(CanJiaTime))
            {
                modelP.strCondition += " and CanJiaTime like '%" + CanJiaTime + "%' ";
            }
            if (!string.IsNullOrEmpty(JieGuo))
            {
                modelP.strCondition += " and JieGuo like '%" + JieGuo + "%' ";
            }
            if (!string.IsNullOrEmpty(JIWang))
            {
                modelP.strCondition += " and JIWang like '%" + JIWang + "%' ";
            }
            if (!string.IsNullOrEmpty(CaiXue))
            {
                modelP.strCondition += " and CaiXue like '%" + CaiXue + "%' ";
            }
            if (!string.IsNullOrEmpty(FuCha))
            {
                modelP.strCondition += " and FuCha like '%" + FuCha + "%' ";
            }
            if (!string.IsNullOrEmpty(JieGuoHIV))
            {
                modelP.strCondition += " and JieGuoHIV like '%" + JieGuoHIV + "%' ";
            }
            if (!string.IsNullOrEmpty(WeiJianCe))
            {
                modelP.strCondition += " and WeiJianCe like '%" + WeiJianCe + "%' ";
            }
            if (!string.IsNullOrEmpty(Desc))
            {
                modelP.strCondition += " and Desc like '%" + Desc + "%' ";
            }
            if (!string.IsNullOrEmpty(State))
            {
                modelP.strCondition += " and State like '%" + State + "%' ";
            }
            if (!string.IsNullOrEmpty(StateTime))
            {
                modelP.strCondition += " and StateTime like '%" + StateTime + "%' ";
            }
            if (Id != 0)
            {
                modelP.strCondition += " and Id =" + Id + " ";
            }
            if (Status != 0)
            {
                modelP.strCondition += " and Status =" + Status + " ";
            }
            if (Creator != 0)
            {
                modelP.strCondition += " and Creator =" + Creator + " ";
            }
            if (!string.IsNullOrEmpty(Created))
            {
                modelP.strCondition += " and Created like '%" + Created + "%' ";
            }
            if (Modifier != 0)
            {
                modelP.strCondition += " and Modifier =" + Modifier + " ";
            }
            if (!string.IsNullOrEmpty(Modified))
            {
                modelP.strCondition += " and Modified like '%" + Modified + "%' ";
            }
            if (!string.IsNullOrEmpty(Images))
            {
                modelP.strCondition += " and Images like '%" + Images + "%' ";
            }

            #endregion

            var logStr = new StringBuilder();
            logStr.Append("------------------------------").AppendLine();
            logStr.Append("客户端数据下载：\r\n").Append("操作用户：").Append(UserName).Append("\r\n").Append("设备号：").Append(deviceNo).Append("\r\n");

            // 只更新Change<>0的数据
            //pager.strCondition += " and Change<>0 ";

            // 记录当前时间
            var doTime = DateTime.Now;
            var lastDownKey = 0L;

            // 初始化或设备号为空均为全部下载
            if (init == 0 && !string.IsNullOrWhiteSpace(deviceNo))
            {
                // 读取数据库上次更新的时间节点
                var lastDown = DBUtility.DbHelperSQL.Query("SELECT * FROM DownDataLog WHERE UserName='" + UserName + "' AND DeviceNo='" + deviceNo + "'").Tables[0];
                string lastTime;
                if (lastDown.Rows.Count > 0)
                {
                    lastTime = lastDown.Rows[0]["LastTime"].ToString();
                    lastDownKey = (long)lastDown.Rows[0]["Id"];

                    modelP.strCondition += " and (Created >='" + lastTime + "' or Modified >='" + lastTime + "') ";

                    logStr.Append("本次更新的时间起始点为：").Append(lastTime).AppendLine();
                }
            }
            logStr.Append("本次客户端下载数据条件：").Append(modelP.strCondition).AppendLine();

            modelP = DBUtility.DbHelperSQL.GetPage(modelP);

            logStr.Append("本次客户端下载数据共生成：").Append(modelP.dt.Rows.Count).AppendLine();
            logStr.Append("符合条件的数据：").Append(modelP.counts).AppendLine();

            List<XQ.SP.Model.UserInfoCheck2Item> list = bllBase.DataTableToList2(modelP.dt);

            // 计算页数
            var pageTotal = Math.Ceiling(modelP.counts * 1.0 / pageSize);

            logStr.Append("取数分页情况：").Append(pageNo).Append("/").Append(pageTotal).AppendLine();

            if (pageNo >= pageTotal)
            {
                // 记录更新时间节点
                if (lastDownKey == 0)
                {
                    DBUtility.DbHelperSQL.ExecuteSql("INSERT INTO dbo.DownDataLog (UserName, DeviceNo, LastTime) VALUES ('" + UserName + "', '" + deviceNo + "', '" + doTime.ToString("yyyy/M/d HH:mm:ss") + "')");
                }
                else
                {
                    DBUtility.DbHelperSQL.ExecuteSql("UPDATE dbo.DownDataLog SET UserName='" + UserName + "', DeviceNo='" + deviceNo + "', LastTime='" + doTime.ToString("yyyy/M/d HH:mm:ss") + "' WHERE Id=" + lastDownKey);
                }
            }
            logStr.Append("------------------------------");

            // 记录日志
            XM.ExceptionAttribute.HandleLog(logStr.ToString(), UserName);

            JsonSerializerSettings serializer = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };

            //var dict = new Dictionary<string, string>();
            //dict.Add("total", pager.counts.ToString());
            //dict.Add("data", JsonConvert.SerializeObject(list, Formatting.Indented, serializer).Replace("\r\n", "").Replace(" ", ""));

            HttpContext.Response.AppendHeader("total", modelP.counts.ToString());

            return new ContentResult
            {
                Content = JsonConvert.SerializeObject(list, Formatting.Indented, serializer).Replace("\r\n", ""),
                ContentType = "application/json"
            };
        }


        //上传数据 单
        //[ValidateInput(false)]
        [Description("实体列表接口")]
        [PermissionFilter]
        public JsonResult Add(string s, string userName, string password)
        {
            var logStr = new StringBuilder();
            logStr.Append("客户端单条数据上传：\r\n").Append("用户：").Append(userName).Append("，密码：").Append(password).Append("\r\n")
                .Append("上传数据：").Append(s).Append("\r\n");


            UserInfoItem userInfo = new UserInfoItem();
            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                XQ.SP.BllServices.UserInfoBLL bllU = new UserInfoBLL();
                userInfo = bllU.GetModelWhereStr(" UserName='" + userName + "' and Pwd='" + password + "' ");
                if (userInfo == null)
                {
                    logStr.Append("用户名或密码错误");
                    return Json("false", JsonRequestBehavior.AllowGet);
                }
            }

            // 记录日志
            XM.ExceptionAttribute.HandleLog(logStr.ToString(), "Teamp_Add\\" + userName);


            UserInfoCheckItem model = JsonConvert.DeserializeObject<UserInfoCheckItem>(s);
            model.Citys = model.Citys.Trim();
            model.Towns = model.Towns.Trim();
            model.Village = model.Village.Trim();
            model.Change = 0;

            // 判断是否已经存在
            var m = bllBase.GetModelWhereStr(" UID='" + model.UID + "' ");
            if (m == null)
            {
                m = new UserInfoCheckItem();
            }

            if (m.Id > 0)
            {
                model.Id = m.Id;
                model.Modified = DateTime.Now;
                if (model.Modifier == 0)
                    model.Modifier = userInfo.Id;
                if (!bllBase.Update(model))
                {
                    XM.ExceptionAttribute.HandleLog("更新数据出错", userName);
                    return Json("false", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (model.Creator == 0)
                    model.Creator = userInfo.Id;
                model.Created = DateTime.Now;
                if (bllBase.Add(model) > 0)
                {
                    XM.ExceptionAttribute.HandleLog("新增数据出错", userName);
                    return Json("false", JsonRequestBehavior.AllowGet);
                }
            }
            return Json("true", JsonRequestBehavior.AllowGet);
        }

        //上传数据 单
        //[ValidateInput(false)]
        [Description("实体列表接口")]
        [PermissionFilter]
        [HttpPost]
        public JsonResult BatchUpdate()
        {
            // 生成操作导入批次号
            var batchNo = DateTime.Now.ToString("yyyyMMddHHmmssffff") + (new Random()).Next(10000, 99999);

            XM.ExceptionAttribute.HandleLog("1、步入手机端批量上传接口\r\n操作批次：" + batchNo);

            Stream stream = Request.InputStream;
            stream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[(int)stream.Length];
            stream.Read(buffer, 0, (int)stream.Length);

            //byte[] utf8Bytes = Encoding.Convert(Encoding.Default, Encoding.UTF8, buffer);
            string json = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

            // 字节长度
            //XM.ExceptionAttribute.HandleLog("2、数据接收完成，字符串长度:" + json.Length);
            XM.ExceptionAttribute.HandleLog("2、数据接收完成\r\n操作批次：" + batchNo + "\r\n接收内容：" + json);

            List<UserInfoCheckItem> s = new List<UserInfoCheckItem>();
            string userName = string.Empty, password = string.Empty;
            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer()
                {
                    MaxJsonLength = Int32.MaxValue
                };
                //var obj = serializer.Deserialize<ParamModel>(json);
                var obj = JsonConvert.DeserializeObject<ParamModel>(json);

                s = (List<UserInfoCheckItem>)obj.s;
                userName = obj.userName;
                password = obj.password;
            }
            catch (Exception ex)
            {
                XM.ExceptionAttribute.HandleLog("3、数据接收并解析出错\r\n操作批次：" + batchNo + "\r\n异常：" + ex.Message);
            }

            XM.ExceptionAttribute.HandleLog("3、数据接收并解析完成\r\n操作批次：" + batchNo + "\r\n用户：" + userName + "\r\n密码：" + password + "\r\n数据：" + s.Count, userName);

            List<UserInfoCheckItem> list = s;

            // TODO 逐渐校正县乡村错误问题
            string city = string.Empty,
                town = string.Empty,
                village = string.Empty;

            UserInfoItem userInfo = new UserInfoItem();
            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                XQ.SP.BllServices.UserInfoBLL bllU = new UserInfoBLL();
                userInfo = bllU.GetModelWhereStr(" UserName='" + userName + "' and Pwd='" + password + "' ");
                if (userInfo == null)
                {
                    XM.ExceptionAttribute.HandleLog("3.1用户名密码错误", userName);
                    return Json("false", JsonRequestBehavior.AllowGet);
                }
                city = userInfo.City;
                town = userInfo.Towns;
                village = userInfo.Village;
            }

            // 生成批量导入DataTable
            DataTable dt1 = new DataTable();
            #region
            dt1.Columns.AddRange(new DataColumn[] {   
                            new DataColumn("No",typeof(string)),  
                            new DataColumn("Citys",typeof(string)),  
                            new DataColumn("Towns",typeof(string)),  
                            new DataColumn("Village",typeof(string)),  
                            new DataColumn("Name",typeof(string)),  
                            new DataColumn("Sex",typeof(string)),  
                            new DataColumn("UID",typeof(string)),  
                            new DataColumn("Nation",typeof(string)),   
                            new DataColumn("ZhiYe",typeof(string)), 
                            new DataColumn("HunYing",typeof(string)),  
                            new DataColumn("WenHua",typeof(string)),
                            new DataColumn("ShangHu",typeof(string)),  
                            new DataColumn("BuNaRu",typeof(string)),  
                            new DataColumn("YiNian",typeof(string)),  
                            new DataColumn("CanJiaTi",typeof(string)),  
                            new DataColumn("CanJiaJian",typeof(string)),  
                            new DataColumn("CanJiaTime",typeof(DateTime)),  
                            new DataColumn("JieGuo",typeof(string)),  
                            new DataColumn("JIWang",typeof(string)),  
                            new DataColumn("CaiXue",typeof(string)),  
                            new DataColumn("FuCha",typeof(string)),  
                            new DataColumn("JieGuoHIV",typeof(string)),  
                            new DataColumn("WeiJianCe",typeof(string)),  
                            new DataColumn("Desc",typeof(string)),  
                            new DataColumn("State",typeof(string)),  
                            new DataColumn("StateTime",typeof(DateTime)),  
                            new DataColumn("Id",typeof(long)),  
                            new DataColumn("Status",typeof(int)),  
                            new DataColumn("Creator",typeof(long)),  
                            new DataColumn("Created",typeof(string)),  
                            new DataColumn("Modifier",typeof(long)),  
                            new DataColumn("Modified",typeof(DateTime)),  
                            new DataColumn("Images",typeof(string)),  
                            new DataColumn("BatchNo",typeof(string)),  
                            new DataColumn("Change",typeof(short))
                        });
            #endregion

            XQ.SP.BllServices.UserInfoCheckBLL bllui = new XQ.SP.BllServices.UserInfoCheckBLL();

            // 开始记录操作日志
            XM.ExceptionAttribute.HandleLog("4、开始组织导入数据\r\n操作批次：" + batchNo, userName);

            var repeat = new List<string>();
            var delete = new List<string>();

            for (int i = 0, l = list.Count; i < l; i++)
            {
                var model = list[i];
                model.Change = model.isChange;

                //// 校验删除无用的身份证
                //if (model.isChange == -1)
                //{
                //    var count = bllui.GetModelList(" UID = '" + model.UID + "'");
                //    if (count.Count == 1)
                //    {
                //        var res = bllui.Delete(count[0].Id);

                //        XM.ExceptionAttribute.HandleLog("4.1、处理数据，删除无用身份证\r\n操作批次：" + batchNo + "\r\n删除身份证：" + count[0].UID + "," + count[0].Id + "\r\n结果：" + res, userName);
                //    }
                //    continue;
                //}


                //model.Citys = model.Citys.Trim();
                //model.Towns = model.Towns.Trim();
                //model.Village = model.Village.Trim();

                // TODO 逐渐校正县乡村错误的问题
                model.Citys = string.IsNullOrWhiteSpace(city) ? model.Citys.Trim() : city.Trim();
                model.Towns = string.IsNullOrWhiteSpace(town) ? model.Towns.Trim() : town.Trim();
                model.Village = string.IsNullOrWhiteSpace(village) ? model.Village.Trim() : village.Trim();

                // 校验姓名不能为空
                if (string.IsNullOrEmpty(model.Name.Trim()))
                {
                    continue;
                }

                #region Insert

                DataRow dr1 = dt1.NewRow();
                dr1[0] = model.No;
                dr1[1] = model.Citys;
                dr1[2] = model.Towns.ToString();
                dr1[3] = model.Village;
                dr1[4] = model.Name;
                dr1[5] = model.Sex;
                dr1[6] = model.UID.ToUpper();
                dr1[7] = model.Nation;
                dr1[8] = model.ZhiYe;
                dr1[9] = model.HunYing;
                dr1[10] = model.WenHua;
                dr1[11] = model.ShangHu;
                dr1[12] = model.BuNaRu;
                dr1[13] = model.YiNian;
                dr1[14] = model.CanJiaTi;
                dr1[15] = model.CanJiaJian;
                if (model.CanJiaTime > DateTime.MinValue)
                {
                    dr1[16] = model.CanJiaTime;
                }
                dr1[17] = model.JieGuo;
                dr1[18] = model.JiWang;
                dr1[19] = model.CaiXue;
                dr1[20] = model.FuCha;
                dr1[21] = model.JieGuoHIV;
                dr1[22] = model.WeiJianCe;
                dr1[23] = model.Desc;
                dr1[24] = model.State;
                dr1[28] = userInfo.Id;
                dr1[29] = model.Created == DateTime.MinValue ? DateTime.Now : model.Created;
                dr1[30] = userInfo.Id;
                dr1[31] = model.Modified == DateTime.MinValue ? DateTime.Now : model.Modified;
                dr1[32] = model.Images;
                dr1[33] = batchNo;
                dr1[34] = 0;

                dt1.Rows.Add(dr1);

                #endregion
            }

            // 开始记录操作日志
            XM.ExceptionAttribute.HandleLog("5、数据组织完成，开始执行导入操作（BulkCopy）\r\n操作批次：" + batchNo + "\r\n导入数据行数：" + dt1.Rows.Count, userName);

            // 批量插入
            if (dt1.Rows.Count > 0)
            {
                if (!bllui.BulkCopy(dt1, batchNo, 5000, true))
                {
                    // 开始记录操作日志
                    XM.ExceptionAttribute.HandleLog("6、执行导入操作（BulkCopy）异常\r\n操作批次：" + batchNo, userName);

                    throw new Exception("批量导入出现异常");
                }
            }

            XM.ExceptionAttribute.HandleLog("6、导入数据执行结束。操作批次：" + batchNo, userName);

            return Json("true", JsonRequestBehavior.AllowGet);
        }

        //上传图片
        [Description("实体列表接口")]
        [PermissionFilter]
        public JsonResult UploadImage(string UID, string userName)
        {
            var logStr = new StringBuilder();
            logStr.Append("上传图片：\r\n身份证号：").Append(UID).Append("\r\n").Append("上传用户：").Append(userName).Append("\r\n").Append("上传文件：").Append(Request.Files.Count).Append("\r\n");

            if (Request.Files.Count == 0)
            {
                logStr.Append("【Error】图片资源为空");
                XM.ExceptionAttribute.HandleLog(logStr.ToString(), userName);

                return Json("false", JsonRequestBehavior.AllowGet);
            }

            var file = Request.Files[0];

            if (file != null)
            {
                logStr.Append("图片文件名：").Append(file.FileName).Append("\r\n");

                XQ.SP.BllServices.UserInfoCheckBLL bll = new UserInfoCheckBLL();
                var model = bll.GetModelWhereStr(" UID='" + UID + "' ");
                if (model == null)
                {
                    logStr.Append("UID不存在");
                    XM.ExceptionAttribute.HandleLog(logStr.ToString(), userName);

                    return Json("false", JsonRequestBehavior.AllowGet);
                }

                try
                {
                    //string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";

                    XQ.Common.Images img = new XQ.Common.Images();
                    string saveRoot = img.GetPath(string.IsNullOrWhiteSpace(userName) ? "Images/" : userName + "/"),
                        uploadPath = Server.MapPath("~" + saveRoot);

                    //// 保存图片到本地
                    //file.SaveAs(uploadPath + fileName);
                    //img.MakeThumbnail(uploadPath + fileName, uploadPath + "S2000_" + UID + ".jpg", 2000, 2000, "HW");
                    ////img.MakeThumbnail(root + fileName, root + "S_" + UID, 600, 600, "HW");
                    ////img.MakeThumbnail(root + fileName, root + "S160_" + UID, 160, 160, "HW");
                    ////img.MakeThumbnail(root + fileName, root + "S80_" + UID, 80, 80, "HW");

                    string filePath = uploadPath + "S_" + UID + ".jpg";
                    if (System.IO.File.Exists(filePath))
                    {
                        string fileName = Path.GetFileNameWithoutExtension(filePath);
                        System.IO.File.Move(filePath, filePath.Replace("UploadFiles","UploadFiles_Back"));
                    }

                    // 不压缩
                    file.SaveAs(filePath);

                    // 获取文件MD5值
                    logStr.Append("图片MD5：").Append(GetMD5HashFromFile(filePath)).Append("\r\n");

                    model.Images = saveRoot + "S_" + UID + ".jpg";
                    var result = DBUtility.DbHelperSQL.ExecuteSql("UPDATE dbo.UserInfoCheck SET Images='" + model.Images + "' WHERE UID='" + UID + "'");

                    //XQ.Common.Files.DeleteFile(uploadPath + fileName);


                    logStr.Append("存储图片：").Append(model.Images).Append("\r\n").Append("更新数据库状态：").Append(result);
                    XM.ExceptionAttribute.HandleLog(logStr.ToString(), userName);
                }
                catch (Exception ex)
                {
                    XM.ExceptionAttribute.HandleLog("上传图片：" + ex.Message, userName);
                    return Json("false", JsonRequestBehavior.AllowGet);
                }

                return Json("true", JsonRequestBehavior.AllowGet);
            }
            else
            {
                logStr.Append("上传图片资源为空");
                XM.ExceptionAttribute.HandleLog(logStr.ToString(), userName);

                return Json("false", JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }


        [HttpPost]
        public string UpdateImageOne(string UID)
        {
            var file = Request.Files["Filedata"];

            if (file != null)
            {
                // 后缀
                var fileExt = file.FileName.Substring(file.FileName.IndexOf("."));

                //string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + fileExt;

                XQ.Common.Images img = new XQ.Common.Images();
                string saveRoot = img.GetPath("Images/"),
                    uploadPath = Server.MapPath("~" + saveRoot);

                string filePath = uploadPath + "S_" + UID + ".jpg";
                if (System.IO.File.Exists(filePath))
                {
                    string fileName = Path.GetFileNameWithoutExtension(filePath);
                    System.IO.File.Move(filePath, filePath.Replace("UploadFiles", "UploadFiles_Back"));
                }

                file.SaveAs(filePath);
                //img.MakeThumbnail(uploadPath + fileName, uploadPath + "S2000_" + UID + fileExt, 2000, 2000, "HW");
                //img.MakeThumbnail(root + fileName, root + "S" + UID, 600, 600, "HW");
                //img.MakeThumbnail(root + fileName, root + "S160" + UID, 160, 160, "HW");
                //img.MakeThumbnail(root + fileName, root + "S80" + UID, 80, 80, "HW");
                //try
                //{
                //    XQ.Common.Files.DeleteFile(Server.MapPath(uploadPath + fileName));
                //}
                //catch
                //{
                //    try { XQ.Common.Files.DeleteFile(uploadPath + fileName); }
                //    catch { }
                //}

                return saveRoot + "S2000_" + UID + fileExt;
            }
            else
            {
                return "";
            }
        }

        // 处理照片路径
        public void HandleImagesPath()
        {
            string root = "/Resource/UploadFiles/";

            // 获取历史照片记录
            var sql = @"SELECT B.UserName,A.UID,A.Images FROM UserInfoCheck A
LEFT JOIN UserInfo B ON B.City=A.Citys AND B.Towns=A.Towns AND B.Village=A.Village
WHERE A.Images LIKE '/Resource/UploadFiles/2020%'";
            var dataSet = DBUtility.DbHelperSQL.Query(sql);
            if (dataSet.Tables.Count > 0)
            {
                var dt = dataSet.Tables[0];

                XQ.Common.Images img = new XQ.Common.Images();

                foreach (DataRow row in dt.Rows)
                {
                    var oldPath = row["Images"].ToString();
                    oldPath = Server.MapPath("~" + oldPath);
                    if (System.IO.File.Exists(oldPath))
                    {
                        string userName = row["UserName"].ToString(),
                            uid = row["UID"].ToString(),
                            path = root + userName + "/";

                        var uploadPath = Server.MapPath("~" + path);
                        if (!System.IO.Directory.Exists(uploadPath))
                        {
                            System.IO.Directory.CreateDirectory(uploadPath);
                        }
                        uploadPath += "S2000_" + uid + ".jpg";

                        System.IO.File.Copy(oldPath, uploadPath);

                        DBUtility.DbHelperSQL.ExecuteSql("UPDATE dbo.UserInfoCheck SET Images='" + (root + userName + "/S2000_" + uid + ".jpg") + "' WHERE UID='" + uid + "'");

                    }
                }
            }

        }

        // 处理照片实际路径不存在
        public void HandleBlankPath()
        {
            // 获取历史照片记录
            var sql = @"SELECT UID,Images FROM UserInfoCheck WHERE len(Images)>0";
            var dataSet = DBUtility.DbHelperSQL.Query(sql);
            if (dataSet.Tables.Count > 0)
            {
                var dt = dataSet.Tables[0];

                XQ.Common.Images img = new XQ.Common.Images();

                foreach (DataRow row in dt.Rows)
                {
                    var oldPath = row["Images"].ToString();
                    oldPath = Server.MapPath("~" + oldPath);
                    if (!System.IO.File.Exists(oldPath))
                    {
                        var uid = row["UID"].ToString();

                        DBUtility.DbHelperSQL.ExecuteSql(@"INSERT INTO UserInfoCheck_BlankImg (
No,Citys,Towns,Village,Name,Sex,UID,Nation,ZhiYe,HunYing,WenHua,ShangHu,BuNaRu,YiNian,CanJiaTi,CanJiaJian,CanJiaTime,JieGuo,JIWang,CaiXue,FuCha,JieGuoHIV,WeiJianCe,[Desc],State,StateTime,Status,Creator,Created,Modifier,Modified,Images,BatchNo,Change,IsShangHu 
)
SELECT No,Citys,Towns,Village,Name,Sex,UID,Nation,ZhiYe,HunYing,WenHua,ShangHu,BuNaRu,YiNian,CanJiaTi,CanJiaJian,CanJiaTime,JieGuo,JIWang,CaiXue,FuCha,JieGuoHIV,WeiJianCe,[Desc],State,StateTime,Status,Creator,Created,Modifier,Modified,Images,BatchNo,Change,IsShangHu 
FROM UserInfoCheck 
WHERE UID='" + uid + "'");

                    }
                }
            }

        }

        // 手机日志数据导入
        public JsonResult HandleLogData(string path)
        {
            var log = new StringBuilder();

            // 生成操作导入批次号
            var batchNo = DateTime.Now.ToString("yyyyMMddHHmmssffff") + (new Random()).Next(10000, 99999);

            var target = Server.MapPath(path);
            if (System.IO.File.Exists(target))
            {
                log.Append("1、开始读取日志文件\r\n操作批次：").Append(batchNo);
                XM.ExceptionAttribute.HandleLog("1、开始读取日志文件\r\n操作批次：" + batchNo, "Mobile");
                var rows = ReadData(target);

                if (rows.Count > 0)
                {
                    int total = 0;
                    string deviceNo = string.Empty;

                    log.Append("2、开始解析日志数据\r\n操作批次：").Append(batchNo);
                    XM.ExceptionAttribute.HandleLog("2、开始解析日志数据\r\n操作批次：" + batchNo, "Mobile");
                    List<UserInfoCheckItem> list = ResolveData(rows, out total, out deviceNo);
                    log.Append("3、解析日志数据结束\r\n操作批次：").Append(batchNo).Append("\r\n日志条数：").Append(total)
                        .Append("\r\n读取条数：").Append(rows.Count).Append("\r\n解析条数：").Append(list.Count).Append("\r\n设备号：").Append(deviceNo);
                    XM.ExceptionAttribute.HandleLog("3、解析日志数据结束\r\n操作批次：" + batchNo + "\r\n日志条数：" + total
                        + "\r\n读取条数：" + rows.Count
                        + "\r\n解析条数：" + list.Count
                        + "\r\n设备号：" + deviceNo, "Mobile");


                    // 生成批量导入DataTable
                    DataTable dt = new DataTable();
                    #region
                    dt.Columns.AddRange(new DataColumn[] {   
                            new DataColumn("No",typeof(string)),  
                            new DataColumn("Citys",typeof(string)),  
                            new DataColumn("Towns",typeof(string)),  
                            new DataColumn("Village",typeof(string)),  
                            new DataColumn("Name",typeof(string)),  
                            new DataColumn("Sex",typeof(string)),  
                            new DataColumn("UID",typeof(string)),  
                            new DataColumn("Nation",typeof(string)),   
                            new DataColumn("ZhiYe",typeof(string)), 
                            new DataColumn("HunYing",typeof(string)),  
                            new DataColumn("WenHua",typeof(string)),
                            new DataColumn("ShangHu",typeof(string)),  
                            new DataColumn("BuNaRu",typeof(string)),  
                            new DataColumn("YiNian",typeof(string)),  
                            new DataColumn("CanJiaTi",typeof(string)),  
                            new DataColumn("CanJiaJian",typeof(string)),  
                            new DataColumn("CanJiaTime",typeof(DateTime)),  
                            new DataColumn("JieGuo",typeof(string)),  
                            new DataColumn("JIWang",typeof(string)),  
                            new DataColumn("CaiXue",typeof(string)),  
                            new DataColumn("FuCha",typeof(string)),  
                            new DataColumn("JieGuoHIV",typeof(string)),  
                            new DataColumn("WeiJianCe",typeof(string)),  
                            new DataColumn("Desc",typeof(string)),  
                            new DataColumn("State",typeof(string)),  
                            new DataColumn("StateTime",typeof(DateTime)),  
                            new DataColumn("Id",typeof(long)),  
                            new DataColumn("Status",typeof(int)),  
                            new DataColumn("Creator",typeof(long)),  
                            new DataColumn("Created",typeof(string)),  
                            new DataColumn("Modifier",typeof(long)),  
                            new DataColumn("Modified",typeof(DateTime)),  
                            new DataColumn("Images",typeof(string)),  
                            new DataColumn("BatchNo",typeof(string)),  
                            new DataColumn("Change",typeof(short))
                        });
                    #endregion

                    int delCount = 0;
                    for (int i = 0, l = list.Count; i < l; i++)
                    {
                        var model = list[i];

                        model.Citys = model.Citys.Trim();
                        model.Towns = model.Towns.Trim();
                        model.Village = model.Village.Trim();

                        // 校验姓名不能为空
                        if (string.IsNullOrEmpty(model.Name.Trim()))
                        {
                            continue;
                        }

                        // 校验删除无用的身份证
                        if (model.isChange == -1)
                        {
                            delCount += 1;
                            continue;
                        }

                        #region Insert

                        DataRow dr = dt.NewRow();
                        dr[0] = model.No;
                        dr[1] = model.Citys;
                        dr[2] = model.Towns.ToString();
                        dr[3] = model.Village;
                        dr[4] = model.Name;
                        dr[5] = model.Sex;
                        dr[6] = model.UID.ToUpper();
                        dr[7] = model.Nation;
                        dr[8] = model.ZhiYe;
                        dr[9] = model.HunYing;
                        dr[10] = model.WenHua;
                        dr[11] = model.ShangHu;
                        dr[12] = model.BuNaRu;
                        dr[13] = model.YiNian;
                        dr[14] = model.CanJiaTi;
                        dr[15] = model.CanJiaJian;
                        if (model.CanJiaTime > DateTime.MinValue)
                        {
                            dr[16] = model.CanJiaTime;
                        }
                        dr[17] = model.JieGuo;
                        dr[18] = model.JiWang;
                        dr[19] = model.CaiXue;
                        dr[20] = model.FuCha;
                        dr[21] = model.JieGuoHIV;
                        dr[22] = model.WeiJianCe;
                        dr[23] = model.Desc;
                        dr[24] = model.State;
                        dr[28] = 5134;
                        dr[29] = model.Created == DateTime.MinValue ? DateTime.Now : model.Created;
                        dr[30] = 5134;
                        dr[31] = model.Modified == DateTime.MinValue ? DateTime.Now : model.Modified;
                        dr[32] = model.Images;
                        dr[33] = batchNo;
                        dr[34] = model.isChange; // 改变状态

                        dt.Rows.Add(dr);

                        #endregion
                    }

                    // 开始记录操作日志
                    log.Append("4、数据组织完成，开始执行导入操作（BulkCopy）\r\n操作批次：").Append(batchNo).Append("\r\n导入数据行数：").Append(dt.Rows.Count).Append("\r\n删除数据行数：").Append(delCount);
                    XM.ExceptionAttribute.HandleLog("4、数据组织完成，开始执行导入操作（BulkCopy）\r\n操作批次：" + batchNo + "\r\n导入数据行数：" + dt.Rows.Count + "\r\n删除数据行数：" + delCount, "Mobile");

                    // 批量插入
                    XQ.SP.BllServices.UserInfoCheckBLL bllui = new XQ.SP.BllServices.UserInfoCheckBLL();
                    if (dt.Rows.Count > 0)
                    {
                        if (!bllui.BulkCopy(dt, batchNo, 5000, true))
                        {
                            // 开始记录操作日志
                            log.Append("5、执行导入操作（BulkCopy）异常\r\n操作批次：").Append(batchNo);
                            XM.ExceptionAttribute.HandleLog("5、执行导入操作（BulkCopy）异常\r\n操作批次：" + batchNo, "Mobile");

                            throw new Exception("5、批量导入出现异常：批量导入出错！");
                        }
                    }

                    log.Append("6、导入数据执行结束。操作批次：").Append(batchNo);
                    XM.ExceptionAttribute.HandleLog("6、导入数据执行结束。操作批次：" + batchNo, "Mobile");

                    // 修改文件名
                    string extension = System.IO.Path.GetExtension(target);//扩展名 “.aspx”
                    string fileName = System.IO.Path.GetFileNameWithoutExtension(target);// 没有扩展名的文件名 “Default”
                    System.IO.File.Move(target, target.Replace(fileName, fileName + "_OK"));

                }
            }
            else
            {
                log.Append("99、文件不存在。操作批次：").Append(batchNo);
                XM.ExceptionAttribute.HandleLog("99、文件不存在。操作批次：" + batchNo, "Mobile");
            }
            return Json(log.ToString(), JsonRequestBehavior.AllowGet);
        }

        private List<string> ReadData(string path)
        {
            List<string> list = new List<string>();

            StreamReader stream = new StreamReader(path, Encoding.UTF8);

            string line = string.Empty;
            bool isRecord = false;
            while ((line = stream.ReadLine()) != null)
            {
                if (line.Contains("#####") && !line.Contains("######"))  // 5#开始,避免将结束标记识别到
                {
                    isRecord = true;
                    if (list.Count > 0)  // 只留最后一次的数据(最新)
                    {
                        list.Clear();
                    }
                }
                if (line.Contains("######"))  // 6#结束
                {
                    isRecord = false;
                }
                if (isRecord)
                {
                    list.Add(line);
                }
            }
            stream.Close();
            stream.Dispose();

            return list;
        }
        private List<UserInfoCheckItem> ResolveData(List<string> list, out int total, out string deviceNo)
        {
            int tempTotal = 0;
            var tempDeviceNo = string.Empty;

            List<UserInfoCheckItem> data = new List<UserInfoCheckItem>();
            for (int i = 0, l = list.Count; i < l; i++)
            {
                var row = list[i];
                // 2020-08-20 12:45:56	本地全部数据	开始输出，共<14046>条 #####
                if (row.Contains("#####") && !row.Contains("######"))
                {
                    var reg = new Regex(@"\<(\d+)\>");
                    Match ret = reg.Match(row);//匹配
                    if (ret.Success)
                    {
                        if (int.TryParse(ret.Groups[0].Value.Replace("<", "").Replace(">", ""), out tempTotal))
                        {
                            continue;
                        }
                    }
                }
                // 2020-08-20 12:45:56	###	513429_8e6c59fbed303c2b
                else if (row.Contains("###"))
                {
                    tempDeviceNo = row.Substring(row.IndexOf("###") + 3).Trim();
                    continue;
                }
                // 2020-08-20 12:45:57 ## {"BuNaRuOther":"是","CanJiaTi":"是","isChange":0,"Citys":"布拖县","Created":"2020-08-15 13:27:10","Creator":205,"HunYing":"已婚有配偶","id":1,"imagesStatus":"无","JiWang":"否","Modifier":0,"Name":"吴宗兰","Nation":"汉族","No":"291304-0641","Owner":"513429","Sex":"女","State":"是","Status":0,"Towns":"拉果乡","UID":"532126198206061273","Village":"伟木村","WenHua":"小学","ZhiYe":"农民"}
                else if (row.Contains("##"))
                {
                    var json = row.Substring(row.IndexOf("##") + 2).Trim();
                    try
                    {
                        // 解析数据
                        JavaScriptSerializer serializer = new JavaScriptSerializer()
                        {
                            MaxJsonLength = Int32.MaxValue
                        };
                        var obj = JsonConvert.DeserializeObject<UserInfoCheckItem>(json);
                        data.Add(obj);
                    }
                    catch (Exception)
                    {
                        XM.ExceptionAttribute.HandleLog("解析数据出错。JSON：" + json, "Mobile");
                    }
                    continue;
                }
                // 2020-08-20 12:42:40	反馈结束 ######	------------------------结束--------------------------
                else if (row.Contains("######"))
                {
                    break;
                }
            }

            total = tempTotal;
            deviceNo = tempDeviceNo;

            return data;
        }


        public static void HandleException(string ex)
        {
            //string pathStr = System.Environment.CurrentDirectory;
            string pathStr = HttpRuntime.AppDomainAppPath.ToString();
            pathStr += "\\LogWin\\" + DateTime.Now.Year + "\\" + DateTime.Now.Month + "\\" + DateTime.Now.Day + "\\";
            if (!System.IO.Directory.Exists(pathStr))
            {
                System.IO.Directory.CreateDirectory(pathStr);
            }
            DateTime now = DateTime.Now;
            string logpath = string.Format(@"Error_{0}{1}{2}{3}.log", now.Year, now.Month, now.Day, now.Hour);
            logpath = pathStr + logpath;

            FileInfo finfo = new FileInfo(logpath);
            if (!finfo.Exists)
            {
                FileStream fs;
                fs = System.IO.File.Create(logpath);
                fs.Close();
                finfo = new FileInfo(logpath);
            }
            using (FileStream fs = finfo.OpenWrite())
            {
                /**/
                ///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);
                /**/
                ///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);
                w.Write("------------------------------------\r\n");
                //w.Write(ex.ToString() + "\r\n");
                //w.Write(ex.ToString() + "\r\n");
                /**/
                ///写入“Log Entry : ”
                w.Write("\n\rLog Entry : ");
                /**/
                ///写入当前系统时间并换行
                w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());
                /**/
                ///写入日志内容并换行
                w.Write(ex + "\r\n");
                ///**/
                /////写入------------------------------------“并换行
                //w.Write("------------------------------------\r\n");
                //w.Write(ex.ToString() + "\r\n");
                //w.Write(ex.ToString() + "\r\n");
                /**/
                ///清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();
                /**/
                ///关闭写数据流
                w.Close();
            }
        }
    }

    public class ParamModel
    {
        public List<UserInfoCheckItem> s;
        public string userName;
        public string password;
    }

}

